/**********************
*microTables 1.2.11
*
**********************/
;(function($,window,document,undefined){
    "use strict";
    $.fn.microtable = function(options){
      var microtable = function(ele, opt){
        this.element = ele,
        this.defaults = {
          FixedColumns:[],//json数组
          Columns:[],//json数组
          AttachColumns:[],//附加json数组-隐藏列
          Dataurl:"",//数据集url地址
          Datamethod:"local",//可以是本地local也可以是远程remote)
          ExteriorDataSet:[],//数据集url地址为空时,可设置取得的外部数据集
          Order:"",//数据默认排序方式-desc,asc
          SortField:"",//数据默认排序字段
          Striped:true,//设置为true将交替显示行背景
          SingleSelect:true,
          Sownumbers:false,//第一列显示自增序列
          Pagination:false,//显示表格底部页脚导航
          //PagePosition:'bottom',//分页栏位置'both',bottom,top
          PageSize:30,//每页显示的记录条数，默认为30
          PageList: [[30, 45, 80, 120, -1], ["30", "45", "80", "120", "全部"]],//设置每页显示记录的下拉菜单
          Fbutton:{"query":true,"add":true,"del":true,"save":true,"refresh":true},
          Width: "640",
          Height: "530",
          Margin: "0",
          Padding: "2",
          Border: "1",
          CheckBoxWidth:"25",
          BottomToolbar:false,
          BottomToolbarWidth:"100%",
          Overflow: "hidden",
          Skin: "Default",
          CheckBox:false,
          CellEdit:false,
          ShowTips:true,
          Tips:{"TipsBackgroundColor":"#FDFDFD","TipsColor":"#2C2F30","TipsBorderColor":"#CCCCCC"},
          EditModel:"click",//click,dblclick-单击,双击
          MouseOverRow:false,//鼠标滑过行
          Vscrollbar:true,
          Hscrollbar:true,
          OnStart: function () {}, 
          OnFinish: function () {}, 
          OnTDClickCell: function (Node,rowIndex,colIndex,Value,Field,DataSet,pageinfo,tableid) {},//单元格单击
          OnTDdblClickCell: function (Node,rowIndex,colIndex,Value,Field,DataSet,pageinfo,tableid) {},//单元格双击
          OnComboClick:function(comboTDnode,Field,comboField,rowIndex,comborowIndex,combocolIndex,comboDataSet,DataSet,pageinfo){},//下拉列表框(combogrid)单击
          OnChkClick:function(rowIndex,SelectedRow,DataSet){},
          OnRefresh:function(DataSet){},//表格刷新时
          OnAdd:function(DataSet){},//表格增加行时
          OnDel:function(Datarow,DataSet){},//表格删除行时Datarow-要删除的行在数据集中的索引
          OnSave:function (DataSet) {},//数据修改后保存 
          OnGetData:function(DataSet){},//数据载入完成后,获取数据集
          OnCellEdit:function(TD,rowIndex,Field,DataSet,CellData,pageinfo){}//单元格编辑(失去焦点后)
        },
        this.options = $.extend({},this.defaults,opt),
        this.table=$(this.element[0]), 
        this.id=this.element[0].id,//本表格的id
        this.tablediv=$("<div></div>"),
        this.tableBodyheader=this.tablediv.clone(true),
        this.tableBody=this.tablediv.clone(true),
        this.tableFixedCol=this.tablediv.clone(true),
        this.tableFixedColheader=this.tablediv.clone(true),
        this.tableBodyheader.addClass("microTable_head"),
        this.tableBody.addClass("microTable_body"),
        this.tableFixedColheader.addClass("microTable_fixedhead"), 
        this.tableFixedCol.addClass("microTable_fixed"),     
        this.tableinit()
      };
      microtable.prototype={//定义表格的方法
        tableinit:function(){//初始化表格
          this.options.OnStart(); 
          var CanEdit=this.options.CellEdit;
          this.tableBody.attr({"id":this.id+"_body"});
          this.table.wrap(this.tableBody);
          var tableid=this.id;
          var tablewidth=0;
          var that=this;
          for (var i=0;i<this.options.Columns.length;i++){//计算不固定列总宽度
            tablewidth+=parseInt(this.options.Columns[i]["width"]);
          }
          var tablefixedwidth=0;
          if (this.options.FixedColumns.length>0){
            for (var i=0;i<this.options.FixedColumns.length;i++){//计算不固定列总宽度
              tablefixedwidth+=parseInt(this.options.FixedColumns[i]["width"]);
            }
          }        
          var tbwidth=parseInt(tablewidth+1);//表格总宽度
          this.table.parent().wrap('<div class="tablebgwrap" id="'+tableid+'_bgwrap" style="width:'+parseInt(this.options.Width-1)+'px;height:'+this.options.Height+'px;"></div>');
          this.table.parent().wrap('<div class="tablebg" id="'+tableid+'_bg"></div>');
          $("#"+tableid+"_bgwrap").parent().append('<div class="tabletools" id="'+tableid+'_bottomtoolbar" style="width:100%;height:40px;display:none"></div>');      
          this.table.append('<tbody></tbody>');
          var Tbody=this.table.find("tbody");
          var DataSet={};//所有数据集
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列  
            this.tableFixedCol.attr({"id":tableid+"_fixeder"});
            this.table.parent().before(this.tableFixedColheader);
            this.table.parent().before(this.tableFixedCol);
            this.tableFixedColheader.append('<table id="'+tableid+'_fixedhead" cellspacing="0" cellpadding="0" style="table-layout:fixed"><thead></thead></table>');
            this.tableFixedColheader.attr({"id":tableid+"_fixedheader"});
            this.tableFixedCol.append('<table id="'+tableid+'_fixed" cellspacing="0" cellpadding="0" style="table-layout:fixed"><tbody></tbody></table>');
            var tablefixedheader=$("#"+tableid+"_fixedheader");
            var tablefixeder=$("#"+tableid+"_fixeder");
            var TFhead=this.tableFixedColheader.find("thead");
            var TFbody=this.tableFixedCol.find("tbody");
            fixedcolheadhtml+='<tr>';//固定列checkbox头部
            if(this.options.CheckBox){//有checkbox                          
              fixedcolheadhtml+='<th class="th align-center align-middle" rowspan="1" colspan="1" style="width:'+this.options.CheckBoxWidth+'px;padding:'+this.options.Padding+'px;">';//<th>与<td>区别在于<th>里的内容以粗体表示
                fixedcolheadhtml+='<input id="'+tableid+'_checkAll" type="checkbox"/>';
              fixedcolheadhtml+='</th>';
            }
            for (var i=0;i<this.options.FixedColumns.length;i++){//固定列头部
              fixedcolheadhtml+='<th class="th align-center align-middle" rowspan="1" colspan="1" style="width:'+this.options.FixedColumns[i]["width"]+'px;min-width:'+this.options.FixedColumns[i]["width"]+'px;max-width:'+this.options.FixedColumns[i]["width"]+'px;padding:'+this.options.Padding+'px;">'+this.options.FixedColumns[i]["title"]; 
              fixedcolheadhtml+='</th>';
            }
            fixedcolheadhtml+='</tr>';
            TFhead.append(fixedcolheadhtml);  
          }//如果有固定列
          this.table.parent().before(this.tableBodyheader);
          this.tableBodyheader.append('<table id="'+tableid+'_head" cellspacing="0" cellpadding="0" style="table-layout:fixed"><thead></thead></table>');
          this.tableBodyheader.attr({"id":tableid+"_header"});
          var tablebg=$("#"+tableid+"_bg");      
          var tableheader=$("#"+tableid+"_header");
          var tablebody=$("#"+tableid+"_body");          
          var Thead=this.tableBodyheader.find("thead");          
          var fixedcolheadhtml='';//固定列头部html
          var fixedcolbodyhtml='';//固定列内容html
          var bodyheadhtml='';//表格头部html
          var bodyhtml='';//表格内容html 
          var fixedcolumnsnum=this.options.FixedColumns.length;
          var columnsnum=this.options.Columns.length;     
          bodyheadhtml+='<tr>';
          for (var i=0;i<this.options.Columns.length;i++){//不固定列头部
            bodyheadhtml+='<th class="th align-center align-middle" rowspan="1" colspan="1" style="width:'+this.options.Columns[i]["width"]+'px;min-width:'+this.options.Columns[i]["width"]+'px;max-width:'+this.options.Columns[i]["width"]+'px;padding:'+this.options.Padding+'px;">'+this.options.Columns[i]["title"]; 
            bodyheadhtml+='</th>';
          }
          bodyheadhtml+='</tr>';
          Thead.append(bodyheadhtml);
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列  
            var thheight=Math.max($("#"+tableid+"_fixedhead >thead >tr >th").height(),$("#"+tableid+"_head >thead >tr >th").height());
            $("#"+tableid+"_fixedhead >thead >tr >th").height(thheight);
            if(this.options.CheckBox){
              var Twidth=tablefixedwidth+parseInt(this.options.CheckBoxWidth);//固定列头部宽度,25-checkbox宽度 
            }else{
              var Twidth=tablefixedwidth;//固定列头部宽度 
            }
            var Theight=thheight+parseInt(this.options.Padding*2+1);//固定列头部高度 
          }else{
            var thheight=$("#"+tableid+"_head >thead >tr >th").height();
            var Twidth=0;//固定列头部宽度
            var Theight=thheight+parseInt(this.options.Padding*2+1);//不固定列头部高度
          }        
          $("#"+tableid+"_head >thead >tr >th").height(thheight);
          this.table.parent().parent().append('<div class="micorTable_scrollY" id="'+tableid+'_scrollY"></div>');
          this.table.parent().parent().append('<div class="micorTable_scrollX" id="'+tableid+'_scrollX"></div>');
                
          tablebg.attr({"style":"margin-left:"+Twidth+"px;width:"+parseInt(this.options.Width-Twidth)+"px;height:"+parseInt(this.options.Height-Theight)+"px;margin-top:"+parseInt(Theight)+"px;"});
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列 
            tablefixedheader.attr({"style":"margin-top:-"+Theight+"px;margin-left:-"+Twidth+"px;"});
          }              
          tableheader.attr({"style":"margin-top:-"+Theight+"px;width:"+tbwidth+"px;left:0px;"});
          $("#"+tableid+"_fixed").attr({"style":"table-layout:fixed;width:"+Twidth+"px;"});  
          if(this.options.BottomToolbar){//底部工具条
            $("#"+tableid+"_bottomtoolbar").css({"display":""});
            $("#"+tableid+"_bottomtoolbar").attr({"style":"width:"+this.options.BottomToolbarWidth+"px;height:40px;"});
            var pagnitionhtml='';
            if (this.options.Pagination){
              pagnitionhtml+='<select id="'+tableid+'_pagelist" title="每页显示记录数" style="float:left;text-align:center;height:22px;width:48px;margin-top:9px;">';
              for (var i=0;i<this.options.PageList[0].length;i++){
                pagnitionhtml+='<option value='+this.options.PageList[0][i]+'>'+this.options.PageList[1][i]+'</option>';
              } 
              pagnitionhtml+='</select>';
              pagnitionhtml+='<div class="pagination-separator"></div>';
              pagnitionhtml+='<div id="'+tableid+'_first" title="首页" class="pagebtn btnfirst"></div>';
              pagnitionhtml+='<div id="'+tableid+'_prv" title="上一页" class="pagebtn btnprv"></div>';
              pagnitionhtml+='<div class="pagination-separator"></div>';
              pagnitionhtml+='<div class="pager">第<input id="'+tableid+'_curpage" type="text" title="当前页码" style="margin:0 4px;padding:0 2px;text-align:center;width:28px;height:22px;" value="1"/>页,共<span id="'+tableid+'_totalpages" style="margin:0 2px;"></span>页</div>';
              pagnitionhtml+='<div class="pagination-separator"></div>';
              pagnitionhtml+='<div id="'+tableid+'_next" title="下一页" class="pagebtn btnnext"></div>';
              pagnitionhtml+='<div id="'+tableid+'_last" title="末页" class="pagebtn btnlast"></div>';
              pagnitionhtml+='<div class="pagination-separator"></div>'; 
            }
            if(this.options.Fbutton["query"]){
              pagnitionhtml+='<div id="'+tableid+'_query" title="查找" class="pagebtn btnquery"></div>';
              pagnitionhtml+='<div class="pagination-separator"></div>';
            }
            if(this.options.Fbutton["add"]){
              pagnitionhtml+='<div id="'+tableid+'_add" title="增加一行" class="pagebtn btnadd"></div>';
            } 
            if(this.options.Fbutton["del"]){
              pagnitionhtml+='<div id="'+tableid+'_del" title="删除选择行" class="pagebtn btndel"></div>'; 
              pagnitionhtml+='<div class="pagination-separator"></div>';
            }
            if(this.options.Fbutton["save"]){
              pagnitionhtml+='<div id="'+tableid+'_save" title="保存" class="pagebtn btnsave"></div>';
            }
            if(this.options.Fbutton["refresh"]){
              pagnitionhtml+='<div id="'+tableid+'_refresh" title="刷新当前页" class="pagebtn btnrefresh"></div>';
            }
            if (this.options.Pagination){
              pagnitionhtml+='<div class="pagerinfo">显示第<span id="'+this.id+'_pagestart"></span>-<span id="'+this.id+'_pageend"></span>条记录,共<span id="'+this.id+'_pagetotal"></span>条记录</div>';
            }
            $("#"+tableid+"_bottomtoolbar").append(pagnitionhtml);
          }else{
            $("#"+tableid+"_bottomtoolbar").css({"display":"none"});
          }
          if (this.options.Datamethod=="local"){//数据库
            $.ajaxSettings.async = false;
            DataSet=this.LoadData({"IsNewData":true,"DataSet":"","Order":this.options.Order,"SortField":this.options.SortField})["DataSet"];
            $.ajaxSettings.async = true;
          }          
          if (this.options.CheckBox) {//如果有checkbox
            $('#'+tableid+'_checkAll').on('click',function(){
              if ($(this).prop("checked") === true) {
                $('input[name="'+tableid+'_checkList"]').prop("checked", $(this).prop("checked"));
                $("#"+tableid+"_fixed").find("tbody >tr").attr({"class":""});
                $("#"+tableid+"_fixed").find("tbody >tr").addClass("selectedRow");
                $("#"+tableid).find("tbody >tr").attr({"class":""});
                $("#"+tableid).find("tbody >tr").addClass("selectedRow");
              }else{
                $('input[name="'+tableid+'_checkList"]').prop("checked", false);
                $("#"+tableid+"_fixed").find("tbody >tr").removeClass("selectedRow");
                $("#"+tableid+"_fixed").find('tr:odd').addClass('oddRow');
                $("#"+tableid+"_fixed").find('tr:even').addClass('evenRow'); 
                $("#"+tableid).find('tr:odd').addClass('oddRow');
                $("#"+tableid).find('tr:even').addClass('evenRow');
              }
            });
            $('input[name="'+tableid+'_checkList"]').on('click',function(){
              var curindex=$(this).parent().parent()[0].rowIndex;//当前行索引
              var Tbtr=$("#"+tableid).find("tbody >tr")[curindex];//不固定列表格行node
              if ($(this).prop("checked") === true){
                $(this).parent().parent().attr({"class":""});
                $(this).parent().parent().addClass("selectedRow");
                $(Tbtr).attr({"class":""});
                $(Tbtr).addClass("selectedRow"); 
              }else{
                $(this).parent().parent().removeClass("selectedRow");
                $(Tbtr).removeClass("selectedRow"); 
                if(curindex%2 ==0){
                 $(this).parent().parent().addClass('evenRow');
                 $(Tbtr).addClass('evenRow');
                }else{
                  $(this).parent().parent().addClass('oddRow');
                  $(Tbtr).addClass('oddRow');
                }
              }
            });
          }
          if(this.options.BottomToolbar){//底部工具条
            $("#"+that.id+"_pagelist").on('change',function(){//页面显示行数改变时
              $.ajaxSettings.async = false;
              DataSet=that.LoadData({"IsNewData":true,"DataSet":"","Order":this.options.Order,"SortField":this.options.SortField})["DataSet"];
              $.ajaxSettings.async = true;
            });
            $("#"+that.id+"_first").on('click',function(){//第1页 
              if(DataSet.length==null){return;}
              $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              if ($("#"+that.id+"_totalpages").text()!=="1"){
                $("#"+that.id+"_curpage").val(1);
                var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                that.LastPage(yushu);
                that.RefreshData(DataSet); 
              } 
            });
            $("#"+that.id+"_prv").on('click',function(){//上1页 
              $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              if ($("#"+that.id+"_totalpages").text()!=="1"){
                var curpage=$("#"+that.id+"_curpage").val();
                if (curpage>1){
                  $("#"+that.id+"_curpage").val(Number(curpage)-1);
                  var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                  that.LastPage(yushu);
                  that.RefreshData(DataSet);
                }
              }  
            });
            $("#"+that.id+"_next").on('click',function(){//下1页
              $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              if ($("#"+that.id+"_totalpages").text()!=="1"){
                var curpage=$("#"+that.id+"_curpage").val();
                if (curpage<Number($("#"+that.id+"_totalpages").text())){
                  $("#"+that.id+"_curpage").val(Number(curpage)+1);
                  var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                  that.LastPage(yushu);
                  that.RefreshData(DataSet);
                }else{
                  $("#"+that.id+"_curpage").val($("#"+that.id+"_totalpages").text());
                } 
              }  
            });
            $("#"+that.id+"_last").on('click',function(){//最后1页 
              if(DataSet.length==null){return;}
              $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              if ($("#"+that.id+"_totalpages").text()!=="1"){
                $("#"+that.id+"_curpage").val(Number($("#"+that.id+"_totalpages").text()));
                var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                that.LastPage(yushu);
                that.RefreshData(DataSet);
              }  
            });
            $("#"+that.id+"_curpage").on('keydown',function(e){//选中某页
              if (e.keyCode == 13) {//回车键按下时
                var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                that.LastPage(yushu);
                that.RefreshData(DataSet);  
              }
            });
            $("#"+that.id+"_refresh").on('click',function(){//刷新页面 
              if(CanEdit){that.options.CellEdit=true;}
              var curpage=$("#"+that.id+"_curpage").val(); 
              $.ajaxSettings.async = false;
              DataSet=that.LoadData({"IsNewData":true,"DataSet":"","Order":that.options.Order,"SortField":that.options.SortField})["DataSet"];
              $.ajaxSettings.async = true;
              Number($("#"+that.id+"_curpage").val())>Number($("#"+that.id+"_totalpages").text())?$("#"+that.id+"_curpage").val($("#"+that.id+"_totalpages").text()):$("#"+that.id+"_curpage").val(curpage);
              var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
              if(curpage==undefined){yushu=DataSet.length;}
              that.LastPage(yushu);
              that.RefreshData(DataSet);
              $("#"+that.id+"_save").unbind("click");//取消保存点击事件
              $("#"+that.id+"_save").on('click',function(){//绑定保存数据 
                that.options.OnSave(DataSet);      
              });
              that.options.OnRefresh(DataSet);    
            });
            $("#"+that.id+"_query").on('click',function(){//查找数据
              var queryrow=0; 
              var strHtml = ''; 
              strHtml += '<ul class="querybg">';
                strHtml += '<li class="querytitle">查找数据';
                  strHtml += '<div id="closefh" class="btnclose" title="关闭"></div>';
                strHtml += '</li>';
                strHtml += '<li id="cxnr" class="querycontent">';
                  strHtml += '<div class="queryrow">';
                    strHtml += '<span style="float:left;margin:6px 0 0 4px;">字段:</span>';
                    strHtml += '<select name="field" title="查询的字段" style="float:left;width:120px;margin:4px;">';
                if (that.options.FixedColumns.length>0){
                  var FTH=that.tableFixedColheader.find("thead >tr");//固定表格tr-node
                  var FTHcolIndexstart=0;
                  var FTHcolIndexend=that.options.FixedColumns.length;
                  if (that.options.CheckBox){
                    FTHcolIndexstart=1;
                    FTHcolIndexend=that.options.FixedColumns.length+1;
                    for (var i=FTHcolIndexstart;i<FTHcolIndexend;i++){
                      strHtml +='<option value='+that.options.FixedColumns[i-1]["field"]+'>'+that.GetCellData(FTH,0,i).replace(/[\r\n]/g,"")+'</option>';
                    } 
                  }else{
                    for (var i=FTHcolIndexstart;i<FTHcolIndexend;i++){
                      strHtml +='<option value='+that.options.FixedColumns[i]["field"]+'>'+that.GetCellData(FTH,0,i).replace(/[\r\n]/g,"")+'</option>';
                    }
                  }
                  var TH=that.tableBodyheader.find("thead >tr");//不固定表格tr-node
                  var THcolIndexstart=0;
                  var THcolIndexend=that.options.Columns.length;
                  for (var i=THcolIndexstart;i<THcolIndexend;i++){
                    strHtml +='<option value='+that.options.Columns[i]["field"]+'>'+that.GetCellData(TH,0,i).replace(/[\r\n]/g,"")+'</option>';//.replace(/[\r\n]/g,"")-去掉回车,换行符
                  }  
                }else{
                  var TH=that.tableBodyheader.find("thead >tr");//不固定表格tr-node
                  var THcolIndexstart=0;
                  var THcolIndexend=that.options.Columns.length;
                  for (var i=THcolIndexstart;i<THcolIndexend;i++){
                    strHtml +='<option value='+that.options.Columns[i]["field"]+'>'+that.GetCellData(TH,0,i).replace(/[\r\n]/g,"")+'</option>';
                  }
                }    
                    strHtml += '</select>';
                    strHtml += '<select name="fh" title="比较符" style="float:left;margin:4px;text-align:center;">';
                      strHtml +='<option value="==" title="等于">=</option>';
                      strHtml +='<option value="!=" title="不等于"><></option>';
                      strHtml +='<option value=">" title="大于">></option>';
                      strHtml +='<option value=">=" title="大于等于">>=</option>';
                      strHtml +='<option value="<" title="小于"><</option>';
                      strHtml +='<option value="<=" title="小于等于"><=</option>';
                    strHtml += '</select>';
                    strHtml += '<input name="zhi" type="text" title="查询值" style="float:left;width:120px;height:20px;margin:4px 0;" placeholder="请输入要查询的值"/>'; 
                    strHtml += '<div id="addfh" title="增加查询条件" class="btnaddfh"></div>';
                  strHtml += '</div>';
                strHtml += '</li>';
                strHtml += '<li class="querytoolbar">';
                  strHtml += '<button id="confirm" type="button" title="确定" class="btnqueryconfirm"/>';
                  strHtml += '<button id="cancel" type="button" title="取消" class="btnquerycancel"/>';
                strHtml += '</li>';
              strHtml += '</ul>'; 
              that.MsgBox('380','200','',strHtml); 
              $('#closefh').on('click',function(){
                MsgBox.remove();
                shadowDiv.remove();  
              });
              $('#addfh').on('click',function(){
                var strHtml='<div class="queryrow">';
                  strHtml += '<span style="float:left;margin:6px 0 0 4px;">字段:</span>';
                    strHtml += '<select name="field" title="查询的字段" style="float:left;width:120px;margin:4px;">';
                  if (that.options.FixedColumns.length>0){
                    var FTH=that.tableFixedColheader.find("thead >tr");//固定表格tr-node
                    var FTHcolIndexstart=0;
                    var FTHcolIndexend=that.options.FixedColumns.length;
                    console.log(FTH);
                    if (that.options.CheckBox){
                      FTHcolIndexstart=1;
                      FTHcolIndexend=that.options.FixedColumns.length+1;
                      for (var i=FTHcolIndexstart;i<FTHcolIndexend;i++){
                        strHtml +='<option value='+that.options.FixedColumns[i-1]["field"]+'>'+that.GetCellData(FTH,0,i)+'</option>';
                      } 
                    }else{
                      for (var i=FTHcolIndexstart;i<FTHcolIndexend;i++){
                        strHtml +='<option value='+that.options.FixedColumns[i]["field"]+'>'+that.GetCellData(FTH,0,i)+'</option>';
                      }
                    }
                    var TH=that.tableBodyheader.find("thead >tr");//不固定表格tr-node
                    var THcolIndexstart=0;
                    var THcolIndexend=that.options.Columns.length;
                    for (var i=THcolIndexstart;i<THcolIndexend;i++){
                      strHtml +='<option value='+that.options.Columns[i]["field"]+'>'+that.GetCellData(TH,0,i).replace(/[\r\n]/g,"")+'</option>';//.replace(/[\r\n]/g,"")-去掉回车,换行符
                    }  
                  }else{
                    var TH=that.tableBodyheader.find("thead >tr");//不固定表格tr-node
                    var THcolIndexstart=0;
                    var THcolIndexend=that.options.Columns.length;
                    for (var i=THcolIndexstart;i<THcolIndexend;i++){
                      strHtml +='<option value='+that.options.Columns[i]["field"]+'>'+that.GetCellData(TH,0,i)+'</option>';
                    } 
                  }    
                    strHtml += '</select>';
                    strHtml += '<select name="fh" title="比较符" style="float:left;margin:4px;text-align:center;">';
                      strHtml +='<option value="==" title="等于">=</option>';
                      strHtml +='<option value="!=" title="不等于"><></option>';
                      strHtml +='<option value=">" title="大于">></option>';
                      strHtml +='<option value=">=" title="大于等于">>=</option>';
                      strHtml +='<option value="<" title="小于"><</option>';
                      strHtml +='<option value="<=" title="小于等于"><=</option>';;
                    strHtml += '</select>';
                    strHtml += '<input name="zhi" type="text" title="查询值" style="float:left;width:120px;height:20px;margin:4px 0;" placeholder="请输入要查询的值"/>'; 
                    strHtml += '<div name="delfh" title="删除查询条件" class="btndelfh"></div>';
                  strHtml +='</div>';
                $('#cxnr').append(strHtml);
                $('input[name="zhi"]').unbind("click");//在绑定点击事件之前先删除绑定事件,否者会执行多次.
                $('[name="zhi"]').each(function(i, v) {//给每个name="zhi"的元素绑定各种函数
                  $(v).on('click', function() {
                    var Field=$('select[name="field"]')[i].value;//当前查询的字段
                    
                  }) 
                });
                $('div[name="delfh"]').unbind("click");//在绑定点击事件之前先删除绑定事件,否者会执行多次.
                $('div[name="delfh"]').on('click',function(){
                  $(this).parent()[0].remove();
                }); 
              });
              $('input[name="zhi"]').unbind("click");//在绑定点击事件之前先删除绑定事件,否者会执行多次.
              $('input[name="zhi"]').on('click',function(){
                //console.log($('input[name="zhi"]').length);
              });
              $('#confirm').unbind("click");//在绑定点击事件之前先删除绑定事件,否者会执行多次.
              $('#confirm').on('click',function(){
                /***查找并重新获得DataSet***/
                var express='';
                for (var i=0;i<$('select[name="field"]').length;i++){
                  if($('input[name="zhi"]')[i].value!=""){//忽略空值
                    if(isNaN($('input[name="zhi"]')[i].value)){//如果不是数值(包含数字和小数,负数),isNaN(x)如果 x 是特殊的非数字值 NaN（或者能被转换为这样的值），返回的值就是 true
                      express+='DataSet.'+$('select[name="field"]')[i].value+$('select[name="fh"]')[i].value+'"'+$('input[name="zhi"]')[i].value+'"';
                      
                    }else{//如果是数值(包含数字和小数,负数)
                      express+='DataSet.'+$('select[name="field"]')[i].value+$('select[name="fh"]')[i].value+$('input[name="zhi"]')[i].value;
                    }
                    if(i<$('select[name="field"]').length-1){
                      express+=' && ';
                    }
                  }    
                }
                var QueryDataSet=DataSet.QueryData(express);
                if(QueryDataSet.length==0){
                  MsgBox.remove();
                  shadowDiv.remove();
                  that.MsgBox('280','150','没有你要的数据!<br>请确认你输入的查询数据是否正确!');    
                }else{
                  var QDataSet=that.LoadData({"IsNewData":false,"DataSet":QueryDataSet})["DataSet"];
                  DataSet=QDataSet;
                  var curpage=$("#"+that.id+"_curpage").val(); 
                  curpage>$("#"+that.id+"_totalpages").text()?$("#"+that.id+"_curpage").val($("#"+that.id+"_totalpages").text()):$("#"+that.id+"_curpage").val(curpage);
                  var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                  that.LastPage(yushu);
                  that.RefreshData(DataSet);
                  //查找到数据后,取消保存功能和表格禁止编辑功能
                  $("#"+that.id+"_save").unbind("click");//取消保存点击事件
                  that.options.CellEdit=false;
                  //查找到数据后,取消保存功能和表格禁止编辑功能
                  MsgBox.remove();
                  shadowDiv.remove();
                } 
              });
              $('#cancel').unbind("click");//在绑定点击事件之前先删除绑定事件,否者会执行多次.
              $('#cancel').on('click',function(){
                MsgBox.remove();
                shadowDiv.remove();
              });           
            });
            $("#"+that.id+"_add").on('click',function(){//增加数据               
              if($("#"+that.id+"_pagelist").val()!=='-1' && $("#"+that.id+"_pagelist").val()!==undefined){//不显示全部数据时               
                $("#"+that.id+"_curpage").val(Number($("#"+that.id+"_totalpages").text()));//先跳转到最后一页
                var TR=$('#'+that.id).find('tbody >tr');
                var TRrows=TR.length;
                if(that.options.ExteriorDataSet.length>0){DataSet=that.options.ExteriorDataSet;}
                if(DataSet.length==null){return;}                 
                var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                that.LastPage(yushu);
                that.RefreshData(DataSet);
                var TRdata={};
                if (yushu==0){
                  if(Number(DataSet.length)>=Number($("#"+that.id+"_pagelist").val())){
                    $("#"+that.id+"_curpage").val(Number($("#"+that.id+"_curpage").val())+1);
                    $("#"+that.id+"_totalpages").html($("#"+that.id+"_curpage").val());
                    $("#"+that.id+"_pagestart").html(DataSet.length+1); 
                  }
                  if (that.options.FixedColumns.length>0){
                    var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                    for (var i=0;i<FTR.length;i++){
                      FTR[i].style.display="none";
                      var colindexstart=0;
                      if (that.options.CheckBox){
                        colindexstart=1;
                      }
                      for (var j=colindexstart;j<FTR[i].cells.length;j++){
                        that.SetCellData(FTR,i,j,"");  
                      }
                    }
                  }else{
                    if (that.options.CheckBox){
                      var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                      for (var i=0;i<FTR.length;i++){
                        FTR[i].style.display="none";
                      }
                    }  
                  }
                  for(var i=0;i<TR.length;i++){
                    TR[i].style.display="none";
                    for (var j=0;j<TR[i].cells.length;j++){
                      that.SetCellData(TR,i,j,"");  
                    }
                  }
                }
                if (yushu<TRrows){
                  if(DataSet.length>0){
                    if (that.options.FixedColumns.length>0){
                      var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                      FTR[yushu].style.display="";
                      var FTRcolIndexstart=0;
                      var FTRcolIndexend=that.options.FixedColumns.length;
                      if (that.options.CheckBox){
                        FTRcolIndexstart=1;
                        FTRcolIndexend=that.options.FixedColumns.length+1; 
                      }
                      for (var i=FTRcolIndexstart;i<FTRcolIndexend;i++){
                        if (that.GetCellAttr(FTR,yushu,i,"type")=="data"){
                          TRdata[that.GetCellAttr(FTR,yushu,i,"field")]=that.GetCellData(FTR,yushu,i);  
                        }
                      }  
                    }else{
                      if (that.options.CheckBox){
                        var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                        FTR[yushu].style.display="";
                      }  
                    }
                    TR[yushu].style.display="";
                    for(var key in DataSet[0]){
                      TRdata[key]='';
                    }
                  }else{
                    if (that.options.FixedColumns.length>0){
                      var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                      FTR[yushu].style.display="";
                      for(var i=0;i<that.options.FixedColumns.length;i++){
                        TRdata[that.options.FixedColumns[i]["field"]]='';
                      }  
                    }else{
                      if (that.options.CheckBox){
                        var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                        FTR[yushu].style.display="";
                      }  
                    }
                    TR[yushu].style.display="";
                    for(var i=0;i<that.options.Columns.length;i++){
                      TRdata[that.options.Columns[i]["field"]]='';
                    }
                    if(that.options.AttachColumns.length>0){//隐藏列信息
                      for(var i=0;i<that.options.AttachColumns.length;i++){
                        TRdata[that.options.AttachColumns[i]["field"]]='';
                      }
                    } 
                  }
                  DataSet.push(TRdata);
                  that.options.OnAdd(DataSet);
                  $("#"+that.id+"_pageend").html(DataSet.length);
                  $("#"+that.id+"_pagetotal").html(DataSet.length);
                  
                }
                $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              }else{//显示全部数据时($("#"+that.id+"_pagelist").val()==-1)
                var TR=$('#'+that.id).find('tbody >tr');
                if(that.options.ExteriorDataSet.length>0){DataSet=that.options.ExteriorDataSet;}
                if(DataSet.length==null){return;}
                var TRdata={};  
                if (that.options.FixedColumns.length>0){
                  var FTR=that.tableFixedCol.find("tbody >tr");//固定表格tr-node
                  var FTRcolIndexstart=0;
                  var FTRcolIndexend=that.options.FixedColumns.length;
                  if (that.options.CheckBox){
                    FTRcolIndexstart=1;
                    FTRcolIndexend=that.options.FixedColumns.length+1; 
                  }
                  for (var i=FTRcolIndexstart;i<FTRcolIndexend;i++){
                    if (that.GetCellAttr(FTR,0,i,"type")=="data"){
                      TRdata[that.GetCellAttr(FTR,0,i,"field")]="";  
                    }
                  }
                }
                for(var key in DataSet[0]){
                  TRdata[key]='';
                }
                DataSet.push(TRdata);
                that.options.OnAdd(DataSet);
                DataSet=that.LoadData({"isNewData":false,"DataSet":DataSet})["DataSet"];
              }        
            });
            $("#"+that.id+"_del").on('click',function(){//删除数据
              var TR=$('#'+that.id).find('tbody >tr');
              var TRrows=TR.length; 
              if(that.options.ExteriorDataSet.length>0){DataSet=that.options.ExteriorDataSet;}
              if(DataSet.length==null){return;}
              if (that.options.CheckBox){
                var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
                var check=false;
                var selecteddatarow=[];
                for(var i=0;i<TRrows;i++){
                  if ($('input[name="'+that.id+'_checkList"]')[i].checked){                  
                    selecteddatarow.push(i);
                    if($("#"+that.id+"_pagetotal").html()!==undefined){
                      $("#"+that.id+"_pagetotal").html(Number($("#"+that.id+"_pagetotal").html())-1);
                    }
                    $('input[name="'+that.id+'_checkList"]')[i].checked=false;
                    TR.removeClass("selectedRow");
                    FTR.removeClass("selectedRow");
                    if(i%2 ==0){
                      TR.addClass('evenRow');
                      FTR.addClass('evenRow');
                    }else{
                      TR.addClass('oddRow');
                      FTR.addClass('oddRow');
                    }
                    check=true; 
                  }
                }
                for(var i=selecteddatarow.length-1;i>=0;i--){
                  var Datarow=Number(selecteddatarow[i]);//当前表格行对应在数据集中的行
                  that.options.OnDel(Datarow,DataSet);
                  DataSet.splice(Datarow,1); //开始位置,删除个数
                } 
                if(!check){
                  that.MsgBox('280','150','请选择要删除的行!');
                }
                if($("#"+that.id+"_pagetotal").html()!==undefined){
                  var yushu=DataSet.length%$("#"+that.id+"_pagelist").val();
                  var totalpages=$("#"+that.id+"_totalpages").html();
                  if(yushu==0 && totalpages!=1){
                    $("#"+that.id+"_totalpages").html(Number(totalpages)-1);
                    $("#"+that.id+"_curpage").val(Number(totalpages)-1);  
                  }
                  that.LastPage(yushu); 
                  that.RefreshData(DataSet);
                }else{
                  that.LastPage(DataSet.length);
                  that.RefreshData(DataSet);
                }
              }
              if($("#"+that.id+"_pagetotal").html()!==undefined){
                $('#'+that.id+'_totalpages').html(that.Pagesize(DataSet.length));
              }     
            });
            $("#"+that.id+"_save").on('click',function(){//保存数据 
              that.options.OnSave(DataSet);      
            });
          }
        },//表格初始化
        Urlfilename:function(url){//获取url地址中的文件名
          url=url.replace(/(.*\/)*([^.]+).*/ig,"$2");	
          return url;
        },
        /******滚动条函数*******
        /**v-垂直滚动
        /**h-水平滚动
        ***********************/
        scroller:function(direction,content,box,scrollbar){
          var cssindex=-1;
          for (var i = 0; i < document.styleSheets.length; i++) {
            if(this.Urlfilename(document.styleSheets[i].href)=="microTables"){
              cssindex=i;
              break;
            };
          };
          var datanum=0;
          $.getJSON(this.options.Dataurl+"?ran="+Math.random(),function(data){
            datanum=data['data'].length;
            return datanum;
          });
          switch (direction){
            case "v":
              var bigHeight = $(content[0]).height();
              var smallHeight = box.height();
              var rate = smallHeight/bigHeight;
              var h = Math.floor(rate*smallHeight);//滚动条高度
              scrollbar.height(h);
              var contentlasttop=bigHeight-smallHeight;
              var offset = box.offset()
              var offsetT = offset.top;
              scrollbar.mousedown(function(e){
                var divOffsetT = scrollbar.offset().top;
                var tempT = e.pageY-divOffsetT;
                function move(e){
                  var newH = e.pageY-tempT-offsetT;//滚动条移动距离
                  if(newH<0){
                    newH=0;
                  }else if(newH>(smallHeight-h)){
                    newH=smallHeight-h;
                  }
                  var rate2 = (newH+h)/smallHeight;
                  var contentH = Math.floor(bigHeight*rate2-smallHeight);
                  for (var i=0;i<content.length;i++){
                    if(contentH<0){contentH=-1;}
                    $(content[i]).css("top",-contentH+"px");
                  }
                  scrollbar.css("top",newH+"px");
                }
                box.on("mousemove",move);//滚动事件只在box内有效
                box.mouseup(function(){
                  box.off("mousemove",move);
                });
              });
              //滚动条鼠标滚轮事件注册
             /* if (box[0].addEventListener) {  //for firefox
                  box[0].addEventListener("DOMMouseScroll", fnMouseWheel);
              }
              box[0].onmousewheel = fnMouseWheel; // for other browser
              //鼠标滚轮事件处理函数
              function fnMouseWheel(e) {
                var evt = e || window.event;
                var wheelDelta = evt.wheelDelta || evt.detail; //鼠标滚动值，可由此判断鼠标滚动方向
                if (wheelDelta=="-120"||wheelDelta=="3"){//向下滚动 
                  var contop = $(content[0]).css("top").replace("px","");//内容顶部坐标
                  var scrtop=scrollbar.css("top").replace("px","");//滚动条顶部坐标
                  var crolldis=document.styleSheets[cssindex].rules[3].style.height.replace("px","");//内容滚动距离
                  var srolldis=parseFloat((smallHeight-h)/(datanum-parseFloat(smallHeight/crolldis)));//滚动条滚动距离
                  var cnewT = Math.abs(parseFloat(contop))+parseFloat(crolldis);//内容新顶部坐标    
                  var snewT=(parseFloat(scrtop)+parseFloat(srolldis)).toFixed(2);//滚动条新顶部坐标
                  if(cnewT+smallHeight<=bigHeight){
                    for (var i=0;i<content.length;i++){
                      $(content[i]).css("top",-cnewT+"px");
                    }
                  }else{
                    for (var i=0;i<content.length;i++){
                      $(content[i]).css("top",-contentlasttop+"px");
                    }  
                  }
                  if(snewT<=smallHeight-h){
                    scrollbar.css("top",snewT+"px");
                  }else{
                    scrollbar.css("top",parseInt(smallHeight-h)+"px");
                  } 
                }
                if (wheelDelta=="120"||wheelDelta=="-3"){//向上滚动
                  var contop = $(content[0]).css("top").replace("px","");//内容顶部坐标
                  var scrtop=scrollbar.css("top").replace("px","");//滚动条顶部坐标
                  var crolldis=document.styleSheets[cssindex].rules[3].style.height.replace("px","");//内容滚动距离
                  var srolldis=parseFloat((smallHeight-h)/(datanum-parseFloat(smallHeight/crolldis)));//滚动条滚动距离
                  var cnewT = Math.abs(parseFloat(contop))-parseFloat(crolldis);//内容新顶部坐标    
                  var snewT=(parseFloat(scrtop)-parseFloat(srolldis)).toFixed(2);//滚动条新顶部坐标
                  if(cnewT>0){
                    for (var i=0;i<content.length;i++){
                      $(content[i]).css("top",-cnewT+"px");
                    }
                  }else{
                    for (var i=0;i<content.length;i++){
                      $(content[i]).css("top","1px");
                    }  
                  }
                  if(snewT>0){
                    scrollbar.css("top",snewT+"px");
                  }else{
                    scrollbar.css("top","0px");
                  }
                }
              }*/
            break;
            case "h":
              var bigWidth = $(content[0]).width();
              var smallWidth = box.width();
              var rate = smallWidth/bigWidth;
              var w = Math.floor(rate*smallWidth);
              scrollbar.width(w);
              var offset = box.offset()
              var offsetL = offset.left;
              scrollbar.mousedown(function(e){
                var divOffsetL = scrollbar.offset().left;
                var tempL = e.pageX-divOffsetL;
                function move(e){
                  var newW = e.pageX-tempL-offsetL;
                  if(newW<0){
                    newW=0;
                  }else if(newW>(smallWidth-w)){
                    newW=smallWidth-w;
                  }
                  var rate2 = (newW+w)/smallWidth;
                  var contentW = Math.floor(bigWidth*rate2-smallWidth);
                  for (var i=0;i<content.length;i++){
                    if (contentW<0){contentW=0;}
                    $(content[i]).css("left",-contentW+"px");
                  }
                  scrollbar.css("left",newW+"px");
                  
                }
                box.on("mousemove",move);
                box.mouseup(function(){
                  box.off("mousemove",move);
                });
              });
            break;
          }
        },
        gettype:function(obj){
          var alltypes ={types : ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]};
          console.log(obj);
        },
        showtips:function(obj){
          if(obj[0]["attributes"]["tips"].value!=''){
            var atips='<div id=tiplayer style="display:none;position:absolute;"></div>';
            $(document.body).append(atips);
            var tipscontent=obj[0]["attributes"]["tips"].value;
            $('#tiplayer').attr({"style":"display:block;border:1px solid "+obj.attr('tipsbordercolor')+";background-color:"+obj.attr('tipsbackgroundcolor')+";font-size:12px;color:"+obj.attr('tipscolor')+";position:absolute;padding:2px;left:"+parseInt(event.x+10)+"px;top:"+parseInt(event.y+10)+"px;z-index:120;"});
            $('#tiplayer')[0].innerHTML=tipscontent.replace("<br>","");
            obj[0]["attributes"]["tips"].value='';
          }
        },
        movetips:function(){
          $("#tiplayer").css({"left":event.x+10+"px","top":event.y+15+"px"});//动态改变用css，动态设置用attr
        },
        deltips:function(){
          if ($('#tiplayer').length>0){
            $('#tiplayer').remove();
          } 
        },
        CheckExpression:function(td,DataSet) {
          var that=this;
          var CTR=$(td).parent();//当前行Node
          var rowIndex=CTR[0].rowIndex;//当前行索引
          var TR=$('#'+that.id).find('tbody >tr');//不固定Node 
          if(that.options.FixedColumns.length>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            for(var i=0;i<that.options.FixedColumns.length;i++){
              if ("caclexp" in that.options.FixedColumns[i]){
                var exps=that.options.FixedColumns[i]["caclexp"];
                var ret = that.CaclExp(td,exps,DataSet);
                if ("format" in that.options.FixedColumns[i]){
                  var format=that.options.FixedColumns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                if (that.options.CheckBox){
                  var FColIndex=i+1;  
                }else{
                  var FColIndex=i;
                }
                that.SetCellData(FTR,rowIndex,FColIndex,fnumber);
                that.UpdateData(FTR[rowIndex]["cells"][i],rowIndex,that.options.FixedColumns,DataSet,fnumber);
              }
              if ("strexp" in that.options.FixedColumns[i]){
                var exps=that.options.FixedColumns[i]["strexp"]["exp"];
                var con=that.options.FixedColumns[i]["strexp"]["connector"];
                var str = that.StrExp(td,con,exps,DataSet);
                if (that.options.CheckBox){
                  var FColIndex=i+1;  
                }else{
                  var FColIndex=i;
                }
                that.SetCellData(FTR,rowIndex,FColIndex,str);
                that.UpdateData(FTR[rowIndex]["cells"][i],rowIndex,that.options.FixedColumns,DataSet,str);
              }
              if ("relatedcacle" in that.options.FixedColumns[i]){
                var exps=that.options.FixedColumns[i]["relatedcacle"];
                var ret = that.RelatedCaclExp(td,exps,DataSet);
                if ("format" in that.options.FixedColumns[i]){
                  var format=that.options.FixedColumns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                if (that.options.CheckBox){
                  var FColIndex=i+1;  
                }else{
                  var FColIndex=i;
                }
                that.SetCellData(FTR,rowIndex,FColIndex,fnumber);
                that.UpdateData(FTR[rowIndex]["cells"][i],rowIndex,that.options.FixedColumns,DataSet,fnumber);
              }
            }
            for(var i=0;i<that.options.Columns.length;i++){
              if ("caclexp" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["caclexp"];
                var ret = that.CaclExp(td, exps,DataSet);
                if ("format" in that.options.Columns[i]){
                  var format=that.options.Columns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                that.SetCellData(TR,rowIndex,i,fnumber);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,fnumber);
              }
              if ("strexp" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["strexp"]["exp"];
                var con=that.options.Columns[i]["strexp"]["connector"];
                var str = that.StrExp(td,con,exps,DataSet);
                that.SetCellData(TR,rowIndex,i,str);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,str);
              }
              if ("relatedcacle" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["relatedcacle"];
                var ret = that.RelatedCaclExp(td,exps,DataSet);
                if ("format" in that.options.Columns[i]){
                  var format=that.options.Columns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                that.SetCellData(TR,rowIndex,i,fnumber);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,fnumber);
              }  
            }
          }else{//没有固定列
            for(var i=0;i<that.options.Columns.length;i++){
              if ("caclexp" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["caclexp"];
                var ret = that.CaclExp(td, exps,DataSet);
                if ("format" in that.options.Columns[i]){
                  var format=that.options.Columns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                that.SetCellData(TR,rowIndex,i,fnumber);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,fnumber);
              }
              if ("strexp" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["strexp"]["exp"];
                var con=that.options.Columns[i]["strexp"]["connector"];
                var str = that.StrExp(td,con,exps,DataSet);
                that.SetCellData(TR,rowIndex,i,str);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,str);
              }
              if ("relatedcacle" in that.options.Columns[i]){
                var exps=that.options.Columns[i]["relatedcacle"];
                var ret = that.RelatedCaclExp(td,exps,DataSet);
                if ("format" in that.options.Columns[i]){
                  var format=that.options.Columns[i]["format"];  
                }else{
                  var format="#.00";
                }
                var fnumber=that.FormatNumber(ret,format);
                that.SetCellData(TR,rowIndex,i,fnumber);
                that.UpdateData(TR[rowIndex]["cells"][i],rowIndex,that.options.Columns,DataSet,fnumber);
              }   
            }
          }
        },
        CaclExp:function(TD, expn,DataSet) {//表达式计算
          var that=this;
          var rowData=that.GetRowData(TD,DataSet); 
          var CTR=$(TD).parent();//当前行Node
          var rowIndex=CTR[0].rowIndex;//当前行索引
          var TR=$('#'+that.id).find('tbody >tr');//不固定Node
          var ColstartIndex=0;//默认不固定列开始索引号
          var ColendIndex=that.options.Columns.length;//默认不固定列结束索引号
          if (that.options.FixedColumns.length>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            var FColstartIndex=0;//默认固定列开始索引号
            var FColendIndex=that.options.FixedColumns.length;//默认固定列结束索引号
            if (that.options.CheckBox){
              FColstartIndex=1;
              FColendIndex=FColendIndex+1;  
            }
            for (var i=FColstartIndex;i<FColendIndex;i++){
              var field=FTR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");//g-执行全局匹配（查找所有匹配而非在找到第一个匹配后停止）
                expn = expn.replace(reg, rowData[field]);
              }
            }  
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");
                expn = expn.replace(reg, rowData[field]);
              }
            }
          }else{//如果没有固定列
            /*if (that.options.CheckBox){
              ColstartIndex=1;
              ColendIndex=ColendIndex+1;  
            }*/
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");
                expn = expn.replace(reg,rowData[field]);
              }
            }
          }
          try {
            return eval(expn);
          } catch (e) {
            return null;
          } 
        },
        RelatedCaclExp:function(TD,expn,DataSet) {//外部数据集表达式计算
          var that=this;
          var rowData=that.GetRowData(TD,DataSet); 
          var CTR=$(TD).parent();//当前行Node
          var rowIndex=CTR[0].rowIndex;//当前行索引
          var TR=$('#'+that.id).find('tbody >tr');//不固定Node
          var ColstartIndex=0;//默认不固定列开始索引号
          var ColendIndex=that.options.Columns.length;//默认不固定列结束索引号
          var exps=expn.express;
          if (that.options.FixedColumns.length>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            var FColstartIndex=0;//默认固定列开始索引号
            var FColendIndex=that.options.FixedColumns.length;//默认固定列结束索引号
            if (that.options.CheckBox){
              FColstartIndex=1;
              FColendIndex=FColendIndex+1;  
            }
            for(var RelatedDataSetName in expn.options.RelatedDataSet){
              var RelatedDataSet=expn.options.RelatedDataSet[RelatedDataSetName];
              if(RegExp(RelatedDataSetName).test(exps)){//判断一个字符串是否包含一个子串的方法-RegExp(字串).test(字符串)
                //var nameinstrindex=exps.indexOf(field);//数据集名称在字符串中的位置索引
                for(var field in RelatedDataSet[expn.options.RelatedRow[RelatedDataSetName]]){
                  var RelatedField=RelatedDataSetName+"."+field;
                  var reg =new RegExp(RelatedField, "g");//g-执行全局匹配（查找所有匹配而非在找到第一个匹配后停止
                  exps=exps.replace(reg,RelatedDataSet[expn.options.RelatedRow[RelatedDataSetName]][field]);                 
                }
              }
            }
            for (var i=FColstartIndex;i<FColendIndex;i++){
              var field=FTR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              var reg = new RegExp(field, "g");//g-执行全局匹配（查找所有匹配而非在找到第一个匹配后停止
              exps = exps.replace(reg,rowData[field]); 
            }
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              var reg = new RegExp(field,"g");
              exps = exps.replace(reg,rowData[field]);
            }  
          }else{
            for(var RelatedDataSetName in expn.options.RelatedDataSet){
              var RelatedDataSet=expn.options.RelatedDataSet[RelatedDataSetName];
              if(RegExp(RelatedDataSetName).test(exps)){//判断一个字符串是否包含一个子串的方法-RegExp(字串).test(字符串)
                //var nameinstrindex=exps.indexOf(field);//数据集名称在字符串中的位置索引
                for(var field in RelatedDataSet[expn.options.RelatedRow[RelatedDataSetName]]){
                  var RelatedField=RelatedDataSetName+"."+field;
                  var reg =new RegExp(RelatedField, "g");//g-执行全局匹配（查找所有匹配而非在找到第一个匹配后停止
                  exps=exps.replace(reg,RelatedDataSet[expn.options.RelatedRow[RelatedDataSetName]][field]);                 
                }
              }
            }
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              var reg = new RegExp(field,"g");
              exps = exps.replace(reg,rowData[field]);
            }
          }
          try {
            return eval(exps);
          } catch (e) {
            return null;
          }
        },
        StrExp:function(TD,con,expn,DataSet){//字段值拼接,字段值内不能出现号
          var that=this;
          var rowData=that.GetRowData(TD,DataSet); 
          var CTR=$(TD).parent();//当前行Node
          var rowIndex=CTR[0].rowIndex;//当前行索引
          var TR=$('#'+that.id).find('tbody >tr');//不固定Node
          var ColstartIndex=0;//默认不固定列开始索引号
          var ColendIndex=that.options.Columns.length;//默认不固定列结束索引号
          if (that.options.FixedColumns.length>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            var FColstartIndex=0;//默认固定列开始索引号
            var FColendIndex=that.options.FixedColumns.length;//默认固定列结束索引号
            if (that.options.CheckBox){
              FColstartIndex=1;
              FColendIndex=FColendIndex+1;  
            }
            for (var i=FColstartIndex;i<FColendIndex;i++){
              var field=FTR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");//g-执行全局匹配（查找所有匹配而非在找到第一个匹配后停止）
                expn = expn.replace(reg, rowData[field]);
              }
            }  
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");
                expn = expn.replace(reg, rowData[field]);
              }
            }
          }else{//如果没有固定列
            /*if (that.options.CheckBox){
              ColstartIndex=1;
              ColendIndex=ColendIndex+1;  
            }*/
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var reg = new RegExp(field, "g");
                expn = expn.replace(reg,rowData[field]);
              }
            }
          }
          expn=expn.replace(/\-/g,"");
          expn=expn.replace(/\+/g,con);
          try {
            return expn;
          } catch (e) {
            return null;
          }
        },
        FormatNumber: function (num, pattern) {//格式化数字
          var strarr = num ? num.toString().split('.') : ['0'];
          var fmtarr = pattern ? pattern.split('.') : [''];
          var retstr = '';
          var str = strarr[0];
          var fmt = fmtarr[0];
          var i = str.length - 1;
          var comma = false;
          for (var f = fmt.length - 1; f >= 0; f--) {
            switch (fmt.substr(f, 1)) {
            case '#':
              if (i >= 0) retstr = str.substr(i--, 1) + retstr;
              break;
            case '0':
              if (i >= 0) retstr = str.substr(i--, 1) + retstr;
              else retstr = '0' + retstr;
              break;
            case ',':
              comma = true;
              retstr = ',' + retstr;
              break;
            }
          };
          if (i >= 0) {
            if (comma) {
              var l = str.length;
              for (; i >= 0; i--) {
                retstr = str.substr(i, 1) + retstr;
                if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
              }
            } else retstr = str.substr(0, i + 1) + retstr;
          };
          retstr = retstr + '.';
          str = strarr.length > 1 ? strarr[1] : '';
          fmt = fmtarr.length > 1 ? fmtarr[1] : '';
          i = 0;
          for (var f = 0; f < fmt.length; f++) {
            switch (fmt.substr(f, 1)) {
            case '#':
              if (i < str.length) retstr += str.substr(i++, 1);
              break;
            case '0':
              if (i < str.length) retstr += str.substr(i++, 1);
              else retstr += '0';
              break;
            }
          };
          return retstr.replace(/^,+/, '').replace(/\.$/, '');
        },
        UpdateData:function(TDnode,rowIndex,Columns,DataSet,Value){//更新数据
          var Field=$(TDnode).attr("field");
          var DataSet=DataSet;
          if(this.options.Pagination){
            var curpage=$("#"+this.id+"_curpage").val();//当前页码
            var pagelist=$("#"+this.id+"_pagelist").val();//页面显示行数
            var rowindex=rowIndex+(Number(curpage)-1)*Number(pagelist);
          }else{
            var rowindex=rowIndex;
          }
          var noparent=true;
          var parentfield="";
          for(var i=0;i<Columns.length;i++){
            if(Columns[i]["field"]==Field && Columns[i]["parentfield"]!==undefined){
              noparent=false;
              parentfield=Columns[i]["parentfield"];
              break;    
            }
          }
          if(noparent){
            DataSet[rowindex][Field]=Value;
          }else{
            DataSet[rowindex][parentfield][Field]=Value;
          }
        },
        Pagesize:function(Num){//获取页码总数Num-数据集的数量.length
          var pagesize=1;
          $("#"+this.id+"_pagelist").val()=="-1"?pagesize=1:pagesize=Math.ceil(Number(Num)/Number($("#"+this.id+"_pagelist").val()));
          return pagesize;
        },
        LoadHead:function(fixedcolumns,columns){
          var Columns=columns;
          if(Columns.length>0){
            var HTR=$("#"+this.id+"_head").find("tr");
            HTR.html("");
            var Headhtml="";
            for (var i=0;i<Columns.length;i++){//不固定列头部
              Headhtml+='<th class="th align-center align-middle" rowspan="1" colspan="1" style="width:'+Columns[i]["width"]+'px;min-width:'+Columns[i]["width"]+'px;max-width:'+Columns[i]["width"]+'px;padding:2px;">'+Columns[i]["title"]; 
              Headhtml+='</th>';
            }
            HTR.append(Headhtml);
          }
          
        },
        /**********************************
        * 载入数据
        * parameter-参数数组
        * parameter={"IsNewData":false,"DataSet":DataSet,"Order":"desc","SortField":""}
        * isNewData-是否是新数据(true-读取数据库文件,false-不读取数据库文件[需设置DataSet])
        * sortField-默认排序字段 
        * order-升序desc或降序asc
        * DataSet-不读取数据库文件时的数据集
        **********************************/
        LoadData:function(parameter){//载入数据
          var that=this;
          var Tbody=$("#"+this.id).find("tbody");
          var fixedcolbodyhtml='',bodyhtml='';
          var tableid=this.id;
          var DataSet={};
          var TRrows=30;
          if($("#"+this.id+"_pagelist").val()!==undefined){
            TRrows=Number($("#"+this.id+"_pagelist").val());//每页显示数据行数-即TR的行数
          }else{
            TRrows=-1;
          }
          var TRstartrow=0;//开始的行索引
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
            var TFbody=this.tableFixedCol.find("tbody");
            TFbody.html("");
          }
          Tbody.html("");
          $("#"+this.id+"_curpage").val(1);
          $("#"+this.id+"_pagestart").html("1");
          if(parameter["IsNewData"]){
            switch(that.options.Datamethod){
              case "local":
                $.getJSON(this.options.Dataurl+"?ran="+Math.random(),function(data){//读取数据库文件,URL参数后加上 "?ran=" + Math.random()是避免缓存的一种很不错的方法！否者不能实时更新数据
                  if(that.options.Order!=="" && that.options.SortField!==""){
                    DataSet=that.SortData(data['data'],parameter["Order"],parameter["SortField"]);
                  }else{
                    DataSet=data['data'];
                  }
                });
              break;
              case "remote":
              
              break;
            }
          }else{
            DataSet=parameter["DataSet"];
          }
          /*if(DataSet.length==0){
            var firstrowdata={};
            if(this.options.FixedColumns.length>0){
              for(var i=0;i<this.options.FixedColumns.length;i++){
                firstrowdata[this.options.FixedColumns[i]["field"]]="";  
              }
            }
            for(var i=0;i<this.options.Columns.length;i++){
              firstrowdata[this.options.Columns[i]["field"]]="";  
            }
            DataSet.push(firstrowdata);
          }*/
          if (TRrows=="-1"){
            TRrows=Number(DataSet.length);  
          }
          that.options.OnGetData(DataSet);
          //通过循环取出data里面的值 
          $.each(DataSet,function(i,value){
            if (i>(TRrows-1)){return false;}
            fixedcolbodyhtml+='<tr microTables-row-index="'+i+'" style="display:">';
            bodyhtml+='<tr microTables-row-index="'+i+'" style="display:">';
            if (that.options.CheckBox){
              fixedcolbodyhtml+='<td type="chk" class="td fixedtd align-center align-middle" rowspan="1" colspan="1" style="width:25px;padding:'+that.options.Padding+'px;">';
                fixedcolbodyhtml+='<input name="'+that.id+'_checkList" type="checkbox"/>';
              fixedcolbodyhtml+='</td>';
            }
            if (that.options.FixedColumns.length>0){//如果有固定列
              for (var j=0;j<that.options.FixedColumns.length;j++){
                fixedcolbodyhtml+='<td type="data" field="'+that.options.FixedColumns[j]["field"]+'" class="td fixedtd '+that.options.FixedColumns[j]["class"]+'" rowspan="1" colspan="1" style="width:'+that.options.FixedColumns[j]["width"]+'px;padding:'+that.options.Padding+'px;color:black;">';
                  if(that.options.FixedColumns[j]["parentfield"]!==undefined){
                    fixedcolbodyhtml+=value[that.options.FixedColumns[j]["parentfield"]][that.options.FixedColumns[j]["field"]];
                  }else{
                    fixedcolbodyhtml+=value[that.options.FixedColumns[j]["field"]];
                  }
                fixedcolbodyhtml+='</td>';
              }
            }
            for (var j=0;j<that.options.Columns.length;j++){
              bodyhtml+='<td type="data" field="'+that.options.Columns[j]["field"]+'" class="td normaltd '+that.options.Columns[j]["class"]+'" rowspan="1" colspan="1" style="width:'+that.options.Columns[j]["width"]+'px;min-width:'+that.options.Columns[j]["width"]+'px;max-width:'+that.options.Columns[j]["width"]+'px;padding:'+that.options.Padding+'px;color:black;">';
              if(that.options.Columns[j]["parentparentfield"]!==undefined){
                for(var k=0;k<value[that.options.Columns[j]["parentparentfield"]][that.options.Columns[j]["parentfield"]].length;k++){
                  if(eval("\""+value[that.options.Columns[j]["parentparentfield"]][that.options.Columns[j]["parentfield"]][k][that.options.Columns[j]["queryfield"]]+"\""+that.options.Columns[j]["logic"]+that.options.Columns[j]["value"])){
                   bodyhtml+=value[that.options.Columns[j]["parentparentfield"]][that.options.Columns[j]["parentfield"]][k][that.options.Columns[j]["field"]];
                   break;
                  }
                }
              }else{
                if(that.options.Columns[j]["parentfield"]!==undefined){
                  bodyhtml+=value[that.options.Columns[j]["parentfield"]][that.options.Columns[j]["field"]];
                }else{
                  bodyhtml+=value[that.options.Columns[j]["field"]];
                }
              }
              bodyhtml+='</td>'; 
            }
            TRstartrow=i;
            fixedcolbodyhtml+='</tr>';
            bodyhtml+='</tr>';     
          }); 
          if(TRstartrow!==TRrows-1){
            for(var i=TRstartrow;i<TRrows-1;i++){
              fixedcolbodyhtml+='<tr microTables-row-index="'+i+'" style="display:none">';
              bodyhtml+='<tr microTables-row-index="'+i+'" style="display:none">';
              if (that.options.CheckBox){
                fixedcolbodyhtml+='<td type="chk" class="td fixedtd align-center align-middle" rowspan="1" colspan="1" style="width:25px;padding:'+that.options.Padding+'px;">';
                  fixedcolbodyhtml+='<input name="'+that.id+'_checkList" type="checkbox"/>';
                fixedcolbodyhtml+='</td>';
              }
              if (that.options.FixedColumns.length>0){//如果有固定列
                for (var j=0;j<that.options.FixedColumns.length;j++){
                  fixedcolbodyhtml+='<td type="data" field="'+that.options.FixedColumns[j]["field"]+'" class="td fixedtd '+that.options.FixedColumns[j]["class"]+'" rowspan="1" colspan="1" style="width:'+that.options.FixedColumns[j]["width"]+'px;padding:'+that.options.Padding+'px;color:black;">';
                    fixedcolbodyhtml+='';
                  fixedcolbodyhtml+='</td>';
                }
              }
              for (var j=0;j<that.options.Columns.length;j++){
                bodyhtml+='<td type="data" field="'+that.options.Columns[j]["field"]+'" class="td normaltd '+that.options.Columns[j]["class"]+'" rowspan="1" colspan="1" style="width:'+that.options.Columns[j]["width"]+'px;min-width:'+that.options.Columns[j]["width"]+'px;max-width:'+that.options.Columns[j]["width"]+'px;padding:'+that.options.Padding+'px;color:black;">';
                  bodyhtml+='';
                bodyhtml+='</td>'; 
              }
              fixedcolbodyhtml+='</tr>';
              bodyhtml+='</tr>';
            }
          }
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
            TFbody.html(fixedcolbodyhtml);
            Tbody.html(bodyhtml);
          }else{
            Tbody.html(bodyhtml);
          }
          var cssindex=-1;
          for (var i = 0; i < document.styleSheets.length; i++) {
            if(this.Urlfilename(document.styleSheets[i].href)=="microTables"){
              cssindex=i;
              break;
            };
          } 
          var tbheight=520;
          var tdheight=24;
          if (cssindex>=0){
            tdheight=document.styleSheets[cssindex].rules[3].style.height.replace("px","");
            tbheight=Number(TRrows)*Number(tdheight)+1;
          }else{
            alert("请先引用microsTables.css文件！");
          }
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
            $("#"+this.id+"_fixeder").attr({"style":"top:"+parseInt(this.options.Border)+"px;margin-left:"+$("#"+this.id+"_fixedheader").css("margin-left")+";height:"+tbheight+"px;"});
          }
          $("#"+this.id+"_body").attr({"style":"top:"+parseInt(this.options.Border)+"px;left:0px;height:"+tbheight+"px;"});
          var Vscrollbar = $("#"+this.id+"_scrollY");
          var Hscrollbar = $("#"+this.id+"_scrollX");
          var Vcontent=["#"+this.id+"_body","#"+this.id+"_fixeder"];
          var Hcontent=["#"+this.id+"_body","#"+this.id+"_header"];
          var Vbox=$("#"+this.id+"_bg");
          if(this.options.Vscrollbar){
            this.scroller("v",Vcontent,Vbox,Vscrollbar);
            Vscrollbar.width()>=$("#"+this.id+"_body").height() ? Vscrollbar[0].style.display="none":Vscrollbar[0].style.display="block";
          }
          if(this.options.Hscrollbar){ 
            this.scroller("h",Hcontent,Vbox,Hscrollbar);
            Hscrollbar.width()>=$("#"+this.id+"_body").width() ? Hscrollbar[0].style.display="none":Hscrollbar[0].style.display="block";
          }
          if(this.options.Striped){
            if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
              TFbody.find('tr:odd').addClass('oddRow');
              TFbody.find('tr:even').addClass('evenRow');
            }
            Tbody.find('tr:odd').addClass('oddRow');
            Tbody.find('tr:even').addClass('evenRow'); 
          }
          if(this.Pagesize(DataSet.length)==0){
            $('#'+this.id+'_totalpages').html('1');
          }else{
            $('#'+this.id+'_totalpages').html(this.Pagesize(DataSet.length));
          }
          $("#"+this.id+"_pagetotal").html(DataSet.length);          
          DataSet.length<Number($("#"+this.id+"_pagelist").val())?$("#"+this.id+"_pageend").html(DataSet.length):$("#"+this.id+"_pageend").html(TRrows);
          var TR=this.table.find("tbody >tr");//不固定表格tr-node
          var TD=TR.find("td");//不固定列td-node
          if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
            var TFTR=this.tableFixedCol.find("tbody >tr");//固定表格tr-node
            var TFTD=TFTR.find("td");//固定列td-node                
          }
          if (this.options.MouseOverRow){//如果开启鼠标滑过行 
            if (this.options.FixedColumns.length>0 || this.options.CheckBox){//如果有固定列
              TFTR.on('mouseover',function(){//固定列表格鼠标滑过行
                var rowindex=this.rowIndex;
                var Tbtr=$("#"+tableid).find("tbody >tr")[rowindex];//不固定列表格行node
                $(this).attr({"class":""});
                $(this).addClass("overRow");
                $(Tbtr).attr({"class":""});
                $(Tbtr).addClass("overRow");
              });
              TFTR.on('mouseout',function(){//固定列表格鼠标滑出行
                var rowindex=this.rowIndex;
                var Tbtr=$("#"+tableid).find("tbody >tr")[rowindex];//不固定列表格行node
                $(this).removeClass("overRow");
                if (that.options.CheckBox){
                  if($(this)[0].cells[0].childNodes[0].checked){//当前行checkbox为true
                    $(this).addClass('selectedRow');
                    $(Tbtr).attr({"class":""});
                    $(Tbtr).addClass('selectedRow');    
                  }else{
                    if(rowindex%2 ==0){
                      $(this).addClass('evenRow');
                      $(Tbtr).removeClass("overRow");
                      $(Tbtr).addClass('evenRow');
                    }else{
                      $(this).addClass('oddRow');
                      $(Tbtr).removeClass("overRow");
                      $(Tbtr).addClass('oddRow');
                    }
                  }
                }else
                {
                  if(rowindex%2 ==0){
                    $(this).addClass('evenRow');
                    $(Tbtr).removeClass("overRow");
                    $(Tbtr).addClass('evenRow');
                  }else{
                    $(this).addClass('oddRow');
                    $(Tbtr).removeClass("overRow");
                    $(Tbtr).addClass('oddRow');
                  }
                }
              });
              TFTD.on('mouseover',function(){//固定列单元格鼠标滑入时
                if (that.options.ShowTips){
                  if(that.options.CheckBox){
                    var colindex=parseInt($(this)[0].cellIndex-1);
                    if (colindex>=0){
                      $(this).attr({"tips":'<span style="font-weight:bold;color:#030F5F;">'+that.options.FixedColumns[colindex]["title"]+"</span>:"+$(this)[0].innerText,"tipsbackgroundcolor":that.options.Tips["TipsBackgroundColor"],"tipscolor":that.options.Tips["TipsColor"],"tipsbordercolor":that.options.Tips["TipsBorderColor"]});
                      if ($(this).attr("tips").substr($(this).attr("tips").length-1,1)!=":"){
                        that.showtips($(this));
                      }else{
                        $(this).attr({"tips":""});  
                      } 
                    } 
                  }else{
                    var colindex=parseInt($(this)[0].cellIndex);
                    $(this).attr({"tips":'<span style="font-weight:bold;color:#030F5F;">'+that.options.FixedColumns[colindex]["title"]+"</span>:"+$(this)[0].innerText,"tipsbackgroundcolor":that.options.Tips["TipsBackgroundColor"],"tipscolor":that.options.Tips["TipsColor"],"tipsbordercolor":that.options.Tips["TipsBorderColor"]});
                    if ($(this).attr("tips").substr($(this).attr("tips").length-1,1)!=":"){
                      that.showtips($(this));
                    }else{
                      $(this).attr({"tips":""});  
                    }
                  } 
                } 
              });
              TFTD.on('mouseout',function(){//固定列单元格鼠标滑出时
                if (that.options.ShowTips){
                  that.deltips();
                }
              });
              TFTD.on('mousemove',function(){//固定列单元格鼠标滑出时
                if (that.options.ShowTips){
                  that.movetips();
                }
              });
            }
            TR.on('mouseover',function(){//不固定列表格鼠标滑过行
              var rowindex=this.rowIndex;
              $(this).attr({"class":""});
              $(this).addClass("overRow");
              if (that.options.FixedColumns.length>0 || that.options.CheckBox){//如果有固定列
                var TFtr=TFbody.find("tr")[rowindex];//固定列表格行node
                $(TFtr).attr({"class":""});
                $(TFtr).addClass("overRow");
              }
            });
            TR.on('mouseout',function(){//不固定列表格鼠标滑出行
              var rowindex=this.rowIndex; 
              if (that.options.FixedColumns.length>0 || that.options.CheckBox){//如果有固定列
                var TFtr=TFbody.find("tr")[rowindex];//固定列表格行node
              }
              $(this).removeClass("overRow");
              if (that.options.CheckBox){
                if($(TFtr)[0].cells[0].childNodes[0].checked){//当前行checkbox为true
                  $(this).addClass('selectedRow');
                  $(TFtr).attr({"class":""});
                  $(TFtr).addClass('selectedRow');  
                }else{
                  if(rowindex%2 ==0){
                    $(this).addClass('evenRow');
                    $(TFtr).removeClass("overRow");
                    $(TFtr).addClass('evenRow');
                  }else{
                    $(this).addClass('oddRow');
                    $(TFtr).removeClass("overRow");
                    $(TFtr).addClass('oddRow');
                  }
                }
              }else
              {
                if(rowindex%2 ==0){
                  $(this).addClass('evenRow');
                  $(TFtr).removeClass("overRow");
                  $(TFtr).addClass('evenRow');
                }else{
                  $(this).addClass('oddRow');
                  $(TFtr).removeClass("overRow");
                  $(TFtr).addClass('oddRow');
                }
              }
            });
            TD.on('mouseover',function(){//不固定列单元格鼠标滑入时
              if (that.options.ShowTips){
                $(this).attr({"tips":'<span style="font-weight:bold;color:#030F5F;">'+that.options.Columns[$(this)[0].cellIndex]["title"]+"</span>:"+$(this)[0].innerText,"tipsbackgroundcolor":that.options.Tips["TipsBackgroundColor"],"tipscolor":that.options.Tips["TipsColor"],"tipsbordercolor":that.options.Tips["TipsBorderColor"]});
                if ($(this).attr("tips").substr($(this).attr("tips").length-1,1)!=":"){
                  that.showtips($(this));
                }else{
                  $(this).attr({"tips":""});  
                } 
              } 
            });
            TD.on('mouseout',function(){//不固定列单元格鼠标滑出时
              if (that.options.ShowTips){
                that.deltips();
              }
            });
            TD.on('mousemove',function(){//不固定列单元格鼠标移动时
              if (that.options.ShowTips){
                that.movetips();
              }
            });
          }//如果开启鼠标滑过行
          //在表格内单击
          if (this.options.FixedColumns.length>0){//如果有固定列
            var TFTD=TFTR.find("td");//固定列td-node
            TFTD.on(this.options.EditModel,function(){
              var FTDnode=this;
              var rowIndex=$(this).parent()[0].rowIndex;
              var colIndex=$(this)[0].cellIndex;
              var cellData=$(this)[0].innerHTML.replace(/& lt;.+?>/gim,'');
              var Field=$(this).attr("field");
              if (that.options.CellEdit){
                if (Field!==undefined)
                {
                  for(var p in that.options.FixedColumns){//遍历json数组时，这么写p为索引(0,1,2等);遍历json对象时每个key/value对,p为key
                    if(that.options.FixedColumns[p]["field"]==Field){
                      if(that.options.FixedColumns[p]["editor"]==undefined){break;}//如果没有编辑器，退出循环
                      switch(that.options.FixedColumns[p]["editor"]["type"]){//编辑器类型
                        case "text":
                          //本列为文本编辑框                          
                          var FTdinput='<input name="td" type="text" class="'+that.options.FixedColumns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>'; 
                          that.CreatTxt(FTDnode,"text",FTdinput,rowIndex,colIndex,that.options.FixedColumns[p],DataSet);
                        break;
                        case "date":
                          var FTdinput='<input name="td" type="text" class="'+that.options.FixedColumns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>'; 
                          that.CreatTxt(FTDnode,"date",FTdinput,rowIndex,colIndex,that.options.FixedColumns[p],DataSet);
                        break;
                        case "textbox":
                          var FTxtarea='<textarea class="'+that.options.FixedColumns[p]["class"]+'" rows="1" cols="20">'+cellData+'</textarea>';
                          that.CreatTxt(FTDnode,"textbox",FTxtarea,rowIndex,colIndex,that.options.FixedColumns[p],DataSet); 
                        break;
                        case "combo":
                          //下拉框
                          var FCombo=that.options.FixedColumns[p]["editor"]["combo"];
                          if(FCombo!==undefined){
                            var FTdinput='<input name="td" type="text" class="'+that.options.FixedColumns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>';
                            that.CreatCombo(FTDnode,rowIndex,colIndex,cellData,Field,FTdinput,that.options.FixedColumns,DataSet,FCombo);
                          }
                        break;
                        case "customfunc":
                          //自定义函数
                          that.options.FixedColumns[p]["editor"]["Func"](FTDnode,rowIndex,colIndex,cellData,Field,DataSet);
                        break;
                        case "undefined":
                        //本列数据不能被编辑,不进行任何操作
                        break;
                      }
                      break;//跳出for循环;跳出each循环,用return false

                    }
                  }
                }    
              }
            });
            TFTD.on('click',function(){
              var FTDnode=this;
              var rowIndex=$(this).parent()[0].rowIndex;
              var colIndex=$(this)[0].cellIndex;
              var cellData=$(this)[0].innerHTML.replace(/& lt;.+?>/gim,'');
              var Field=$(this).attr("field");
              var pagelist=$("#"+that.id+"_pagelist").val();
              var curpage=$("#"+that.id+"_curpage").val();
              var pageinfo={"pagelist":pagelist,"curpage":curpage};
              
              that.options.OnTDClickCell(FTDnode,rowIndex,colIndex,cellData,Field,DataSet,pageinfo,that.id);
            });
            TFTD.on('dblclick',function(){
              var FTDnode=this;
              var rowIndex=$(this).parent()[0].rowIndex;
              var colIndex=$(this)[0].cellIndex;
              var cellData=$(this)[0].innerHTML.replace(/& lt;.+?>/gim,'');
              var Field=$(this).attr("field");
              var pagelist=$("#"+that.id+"_pagelist").val();
              var curpage=$("#"+that.id+"_curpage").val();
              var pageinfo={"pagelist":pagelist,"curpage":curpage};
              that.options.OnTDdblClickCell(FTDnode,rowIndex,colIndex,cellData,Field,DataSet,pageinfo,that.id);
            });
          }
          var TD=TR.find("td");//不固定列td-node
          TD.on(this.options.EditModel,function(){
            var TDnode=this;
            var rowIndex=$(this).parent()[0].rowIndex;
            var colIndex=$(this)[0].cellIndex;
            var cellData=$(this)[0].innerHTML;
            var Field=$(this).attr("field");
            if (that.options.CellEdit){
              if (Field!==undefined){
                for(var p in that.options.Columns){//遍历json数组时，这么写p为索引(0,1,2等);遍历json对象时每个key/value对,p为key
                  if(that.options.Columns[p]["field"]==Field){
                    if(that.options.Columns[p]["editor"]==undefined){break;}//如果没有编辑器，退出循环
                    switch(that.options.Columns[p]["editor"]["type"]){//编辑器类型
                      case "text":
                        //本列为文本编辑框
                        var Tdinput='<input name="td" type="text" class="'+that.options.Columns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>';
                        that.CreatTxt(TDnode,"text",Tdinput,rowIndex,colIndex,that.options.Columns[p],DataSet);
                      break;
                      case "date":
                          var Tdinput='<input name="td" type="text" class="'+that.options.Columns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>'; 
                          that.CreatTxt(TDnode,"date",Tdinput,rowIndex,colIndex,that.options.Columns[p],DataSet);
                        break;
                      case "textbox":
                        var Txtarea='<textarea class="'+that.options.Columns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%; rows="1" cols="20">'+cellData+'</textarea>';
                        that.CreatTxt(TDnode,"textbox",Txtarea,rowIndex,colIndex,that.options.Columns[p],DataSet);
                      break;
                      case "combo":
                        //下拉框  
                        var Combo=that.options.Columns[p]["editor"]["combo"]; 
                        if(Combo!==undefined){
                          var Tdinput='<input name="td" type="text" class="'+that.options.Columns[p]["class"]+'" style="height:'+parseInt(tdheight-that.options.Padding*2-that.options.Border)+'px;width:100%;"/>';
                          that.CreatCombo(TDnode,rowIndex,colIndex,cellData,Field,Tdinput,that.options.Columns,DataSet,Combo);
                        }
                      break;
                      case "customFunc":
                      //自定义函数
                        that.options.Columns[p]["editor"]["Func"](TDnode,rowIndex,colIndex,cellData,Field,DataSet);
                      break;
                      case "undefined":
                      //本列数据不能被编辑,不进行任何操作
                      break;
                    }
                    break;//跳出for循环;跳出each循环,用return false

                  }
                }
              }    
            } 
          });
          //在表格内单击
          TD.on('click',function(){
            var TDnode=this;
            var rowIndex=$(this).parent()[0].rowIndex;
            var colIndex=$(this)[0].cellIndex;
            var cellData=$(this)[0].innerHTML.replace(/& lt;.+?>/gim,'');
            var Field=$(this).attr("field");
            var pagelist=$("#"+that.id+"_pagelist").val();
            var curpage=$("#"+that.id+"_curpage").val();
            var pageinfo={"pagelist":pagelist,"curpage":curpage};
            that.options.OnTDClickCell(TDnode,rowIndex,colIndex,cellData,Field,DataSet,pageinfo,that.id);
          });
          TD.on('dblclick',function(){
            var TDnode=this;
            var rowIndex=$(this).parent()[0].rowIndex;
            var colIndex=$(this)[0].cellIndex;
            var cellData=$(this)[0].innerHTML.replace(/& lt;.+?>/gim,'');
            var Field=$(this).attr("field");
            var pagelist=$("#"+that.id+"_pagelist").val();
            var curpage=$("#"+that.id+"_curpage").val();
            var pageinfo={"pagelist":pagelist,"curpage":curpage};
            that.options.OnTDdblClickCell(TDnode,rowIndex,colIndex,cellData,Field,DataSet,pageinfo,that.id);
          });
          $('input[name="'+this.id+'_checkList"]').click(function(){
            var rowIndex=$(this).parent().parent()[0].rowIndex;
            var SelectedRow=that.SelectedRow();
            that.options.OnChkClick(rowIndex,SelectedRow,DataSet);
          });
          return {"DataSet":DataSet};  
        },
        /******************************************
        *创建文本框
        *TDnode-单元格node
        *Contype-文本框类型
        *TDcontent-文本框内容html
        *DataSet-数据集json
        *******************************************/
        CreatTxt:function(TDnode,Contype,TDcontent,rowIndex,colIndex,Columns,DataSet){
          var ovalue=$(TDnode).text();
          $(TDnode).html('');
          $(TDnode).html(TDcontent);
          var that=this; 
          switch (Contype){
            case "text":
              var sput=$(TDnode).find("input"); 
              sput.blur(function (event) {//失去焦点时
                var Value = $(this).val();
                if (ovalue !== Value) {
                  if(Columns["format"]!==undefined){
                    var format=Columns["format"];
                    Value=that.FormatNumber(Value,format);//格式化当前数据  
                  }
                  that.UpdateData(TDnode,rowIndex,Columns,DataSet,Value);//更新数据集
                };
                $(TDnode).html(Value);
                that.CheckExpression(TDnode,DataSet);
                var pagelist=$("#"+that.id+"_pagelist").val();
                var curpage=$("#"+that.id+"_curpage").val();
                var pageinfo={"pagelist":pagelist,"curpage":curpage};
                that.options.OnCellEdit(TDnode,rowIndex,Columns["field"],DataSet,Value,pageinfo); 
              }).val(ovalue).focus(function(){//有焦点时
                
              }).select();
              $("input[name=td]").click(function(event){//输入框单击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });
              $("input[name=td]").dblclick(function(event){//输入框双击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });              
            break;
            case "date":
              $("input[name=td]").datetimepicker(Columns["editor"]["dateset"]).focus();//输入框获得焦点
              var sput=$(TDnode).find("input"); 
              sput.blur(function (event) {//失去焦点时
                var Value = $(this).val();
                if (ovalue !== Value) {
                  if(Columns["format"]!==undefined){
                    var format=Columns["format"];
                    Value=that.FormatNumber(Value,format);//格式化当前数据  
                  }
                  that.UpdateData(TDnode,rowIndex,Columns,DataSet,Value);//更新数据集
                };
                $(TDnode).html(Value);
                that.CheckExpression(TDnode,DataSet);
                var pagelist=$("#"+that.id+"_pagelist").val();
                var curpage=$("#"+that.id+"_curpage").val();
                var pageinfo={"pagelist":pagelist,"curpage":curpage};
                that.options.OnCellEdit(TDnode,rowIndex,Columns["field"],DataSet,Value,pageinfo); 
              }).val(ovalue).focus(function(){//有焦点时
                
              }).select();
              $("input[name=td]").click(function(event){//输入框单击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });
              $("input[name=td]").dblclick(function(event){//输入框双击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });
            break;
            case "textbox":
              var sput=$(TDnode).find("textarea");
              sput.blur(function (event) {//失去焦点时
                var Value = $(this).val();
                if (ovalue !== Value) {
                  that.UpdateData(TDnode,rowIndex,Columns,DataSet,Value);//更新数据集
                };
                $(TDnode).html(Value);
                var pagelist=$("#"+that.id+"_pagelist").val();
                var curpage=$("#"+that.id+"_curpage").val();
                var pageinfo={"pagelist":pagelist,"curpage":curpage};
                that.options.OnCellEdit(TDnode,rowIndex,Columns["field"],DataSet,Value,pageinfo);
              }).val(ovalue).focus().select();
              $("textarea[name=td]").click(function(event){//输入框单击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });
              $("textarea[name=td]").dblclick(function(event){//输入框双击时
                event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
              });
            break;
          }
        },
        /******************************************
        *创建下拉框
        *TDnode-单元格node
        *rowIndex-行索引
        *colIndex-列索引
        *cellData-单元格值
        *Field-字段
        *TDcontent-单元格html
        *DataSet-数据集json
        *TCombo-下拉框配置json
        *******************************************/
        CreatCombo:function(TDnode,rowIndex,colIndex,cellData,Field,TDcontent,mColumns,DataSet,TCombo){//创建下拉列表(combolist)/下拉表格(combogrid)
          var that=this;
          var OP=TCombo.options;
          var oldvalue=$(TDnode).text();
          $(TDnode).html('');
          $(TDnode).html(TDcontent);
          var colNum=TCombo.columns.length;//下拉列表列数
          var rowNum=[];//下拉列表的值(数组)的个数(行数)-自定义值时使用
          var rowNums=0;
          var comboTable='<div id="combo_'+Field+'bg"  style="position:absolute;top:'+parseInt($('input[name="td"]').offset().top+18)+'px;left:'+$('input[name="td"]').offset().left+'px;z-index:301;border:1px solid #8F8BFB;background-color:#DBDBDB;" cellpadding="0" cellspacing="0">';
          if (OP.Showtitle){
            comboTable+='<div id="combo_'+Field+'header">';
              comboTable+='<table id="combo_'+Field+'head">';
                comboTable+='<thead>';
                  comboTable+='<tr>';
                  for (var i=0;i<colNum;i++){
                    if (TCombo.columns[i]["width"]!=="auto"){
                      comboTable+='<th class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;background-color:#DBDBDB;padding:2px;border:1px solid #C5C5C5;border-bottom:0px solid #C5C5C5;cursor:default;width:'+TCombo.columns[i]["width"]+'px;max-width:'+TCombo.columns[i]["width"]+'px;">';
                    }else{
                      comboTable+='<th class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;background-color:#DBDBDB;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+=TCombo.columns[i].title;//下拉列表标题
                    comboTable+='</th>';
                  }
                  comboTable+='<tr>';
                comboTable+='</thead>';
              comboTable+='</table>';
            comboTable+='</div>';
          }
            comboTable+='<div id="combo_'+Field+'bodier" style="max-height:'+OP["height"]+'px;overflow:auto;border-top: 1px solid #C5C5C5;border-bottom: 1px solid #C5C5C5;border-right: 1px solid #C5C5C5;">';
              comboTable+='<table id="combo_'+Field+'body">';
              comboTable+='<tbody>';
          switch(OP.Datamethod){
            case "text":
              for(var i=0;i<colNum;i++){
                rowNum[i]=TCombo.columns[i].value.length;//下拉列表的值(数组)的个数(行数)  
              }
              rowNums=Math.max.apply(null,rowNum);
            break;
            case "local":
              var getfieldindex=0;////当前单元格对应下拉列表的字段的索引
              for(var i=0;i<colNum;i++){
                if (TCombo.columns[i]["field"]==TCombo.getfield){
                  getfieldindex=i;
                  break;
                }
              }
              var comboDataSet=[]; 
              $.ajaxSettings.async = false;
              $.getJSON(OP.Dataurl+"?ran="+Math.random(),function(data){//读取数据库文件
                comboDataSet=data['data'];
                if(TCombo.queryfieldvalue!=undefined){//如果有要查询的字段
                  comboDataSet=[];
                  var qexpress="";
                  var prekey="";
                  for(var i=0;i<TCombo.queryfieldvalue.length;i++){
                    for (var key in TCombo.queryfieldvalue[i]) {
                      if(prekey==""){
                        if(i==TCombo.queryfieldvalue.length-1){
                          qexpress+='item["'+key+'"]'+TCombo.queryfieldvalue[i][key]+'';
                        }else{
                          qexpress+='(item["'+key+'"]'+TCombo.queryfieldvalue[i][key];
                        }
                        prekey=key;
                        break; 
                      }else{
                        if(i==TCombo.queryfieldvalue.length-1){
                          qexpress+=' item["'+key+'"]'+TCombo.queryfieldvalue[i][key]+')';  
                        }else{
                          qexpress+='item["'+key+'"]'+TCombo.queryfieldvalue[i][key]; 
                        }
                        prekey=key;
                        break;
                      }
                    }                     
                  }
                  comboDataSet=data['data'].filter(function(item){
                    return eval(qexpress);
                  });
                } 
              });
              $.ajaxSettings.async = true;
              rowNums=comboDataSet.length;
            break;
            case "remote":
              var getfieldindex=0;////当前单元格对应下拉列表的字段的索引
              for(var i=0;i<colNum;i++){
                if (TCombo.columns[i]["field"]==TCombo.getfield){
                  getfieldindex=i;
                  break;
                }
              }
              var comboDataSet=[]; 
              $.ajaxSettings.async = false;
              $.getJSON(OP.Dataurl+"?ran="+Math.random(),function(data){//remote读取数据库文件
                comboDataSet=data['data'];
              });
              $.ajaxSettings.async = true;
              rowNums=comboDataSet.length;
            break;
          }
          for(var i=0;i<rowNums;i++){
            comboTable+='<tr>';

            if(OP.blankbreak && (comboDataSet[i][TCombo.getfield].replace(/\s+/g,"")=="" || TCombo.getfield==undefined)){break;}
            for(var j=0;j<colNum;j++){
              switch(OP.Datamethod){
                case "text":
                  if(TCombo.columns[j].value[i]!=undefined){
                    if (TCombo.columns[j]["width"]!=="auto"){
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+TCombo.columns[j]["width"]+'px;">';
                    }else{
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+=TCombo.columns[j].value[i];
                    comboTable+='</td>';
                  }else{
                    if (Combo.columns[j]["width"]!=="auto"){
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+TCombo.columns[j]["width"]+'px;">';
                    }else{
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+='';
                    comboTable+='</td>';
                  }
                break;
                case "local":
                  comboTable+='<td type="data" field="'+TCombo.columns[j]["field"]+'" class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+TCombo.columns[j]["width"]+'px;max-width:'+TCombo.columns[j]["width"]+'px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">';
                    comboTable+=comboDataSet[i][TCombo.columns[j]["field"]]; 
                  comboTable+='</td>';
                break;
                case "remote":
                  comboTable+='<td type="data" field="'+TCombo.columns[j]["field"]+'" class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+TCombo.columns[j]["width"]+'px;max-width:'+TCombo.columns[j]["width"]+'px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">';
                    comboTable+=comboDataSet[i][TCombo.columns[j]["field"]];
                  comboTable+='</td>';
                break;
              }
            } 
            comboTable+='<tr>';  
          }   
                comboTable+='<tbody>';
              comboTable+='</table>';
            comboTable+='</div>';
          comboTable+='</div>';
          if($('#combo_'+Field+'bg').length!==0){
            $('#combo_'+Field+'bg').remove();
          }
          var valChange=false;
          setTimeout(function(){//延时.在没有想到input失去焦点时在不影响下拉列表单击改变单元格数据
            $('body').append(comboTable); 
            $('#combo_'+Field+'body').find("tbody:empty").remove();
            $('#combo_'+Field+'head').find("thead >tr:empty").remove();
            $('#combo_'+Field+'body').find("tbody >tr:empty").remove();
            $('#combo_'+Field+'body').find("tbody >tr:odd").addClass('oddRow');
            $('#combo_'+Field+'body').find("tbody >tr:even").addClass('evenRow'); 
            var comboTR=$('#combo_'+Field+'body').find("tr");
            var comboTD=$('#combo_'+Field+'body').find("td");
            for(var i=0;i<rowNums;i++){
              if(OP.blankbreak && comboDataSet[i][TCombo.getfield].replace(/\s+/g,"")==""){break;}//如果设置有空格就停止 
              switch(OP.Datamethod){
                case "text":
                  if($("input[name=td]").val()==that.GetCellData(comboTR,i,TCombo.getcolval)){
                    comboTR.eq(i).removeClass();
                    comboTR.eq(i).addClass('selectedRow');
                  }
                break;
                case "local": 
                  if($("input[name=td]").val()==that.GetCellData(comboTR,i,getfieldindex)){
                    comboTR.eq(i).removeClass();
                    comboTR.eq(i).addClass('selectedRow');
                    //滚动到当前行
                    
                  }
                break;
                case "remote": 
                  if($("input[name=td]").val()==that.GetCellData(comboTR,i,getfieldindex)){
                    comboTR.eq(i).removeClass();
                    comboTR.eq(i).addClass('selectedRow');
                    //滚动到当前行
                    
                    console.log(comboTR.eq(i)[0].offsetTop);
                  }
                break;
              }
            }
            comboTR.on('mouseover',function(){//表格鼠标滑过行
              var rowindex=this.rowIndex;
              if($(this).attr("class")!=="selectedRow"){
                $(this).attr({"class":""});
                $(this).addClass("overRow");
              }
            });
            comboTR.on('mouseout',function(){//列表格鼠标滑出行
              var rowindex=this.rowIndex; 
              if($(this).attr("class")!=="selectedRow"){
                $(this).removeClass("overRow");
                if(rowindex%2 ==0){
                  $(this).addClass('evenRow');
                }else{
                  $(this).addClass('oddRow');
                }
              }
            });
            comboTD.click(function (event) {//单击时              
              var comboTRrowindex=$(this).parent()[0].rowIndex;
              var newvalue="";
              switch(OP.Datamethod){
                case "text": 
                  newvalue = $(this).parent()[0]["cells"][TCombo.getcolval].innerHTML;
                break;
                case "local":
                  newvalue = $(this).parent()[0]["cells"][getfieldindex].innerHTML;
                break;
                case "remote":
                  newvalue = $(this).parent()[0]["cells"][getfieldindex].innerHTML;
                break;
              }
              if (oldvalue!==newvalue){valChange=true;}
              $("input[name=td]").val(newvalue);
              $(TDnode).html(newvalue);
              if (OP.Datamethod!=="text"){
                if (TCombo.setfield!=={}){
                  //设置相应的字段对应值
                  /*Combo.setfield={"dzmc":"discr","dzxhgg":"xhgg"}
                  * key-Combo.setfield的key值(dzmc)
                  * Combo.setfield[key]-获取对应key的value值(discr)*/
                  for (var key in TCombo.setfield) {
                    var kvalindex=-1;
                    for(var i=0;i<colNum;i++){
                      if (TCombo.columns[i]["field"]==TCombo.setfield[key]){
                        kvalindex=i;//discr对应在下拉列表中的列索引
                        break;
                      }
                    }
                    if (kvalindex!==-1){//要设置的字段在下拉表中有对应的字段
                      var combokeydata=that.GetCellData(comboTR,comboTRrowindex,kvalindex);//下拉列表key值对应单元格的数据
                      var mtableindex=-1;//dzmc对应在主表中的列索引默认为第1列,如果在固定列和非固定列中都有key值则以固定列为准
                      for(var i=0;i<that.options.Columns.length;i++){//先在非固定列中查找key对应的列
                        if (that.options.Columns[i]["field"]==key){
                          mtableindex=i;//dzmc对应在主表中的列索引
                          var TR=$('#'+that.id).find('tr');
                          var columns=that.options.Columns;
                          break;
                        }
                      }
                      if(that.options.FixedColumns.length>0){//主表有固定列,再在固定列中查找key对应的列
                        for(var i=0;i<that.options.FixedColumns.length;i++){
                          if (that.options.FixedColumns[i]["field"]==key){
                            mtableindex=i;//dzmc对应在主表中的列索引
                            var TR=$('#'+that.id+'_fixed').find('tr');
                            var columns=that.options.FixedColumns;
                            break;
                          }
                        }
                      }
                      if (mtableindex!==-1){//在主表有相应的字段索引
                        that.SetCellData(TR,rowIndex,mtableindex,combokeydata); //设置主表对应值
                        var mTDnode=TR[rowIndex]["cells"][mtableindex];//主表对应的TDnode
                        that.UpdateData(mTDnode,rowIndex,columns,DataSet,combokeydata);//更新数据集
                      }
                    }else{//要设置的字段在下拉表中没有对应的字段
                      var pagelist=$("#"+that.id+"_pagelist").val();
                      var curpage=$("#"+that.id+"_curpage").val();
                      var Datarow=rowIndex;//当前表格行对应在数据集中的行
                      if(pagelist!==undefined && curpage!==undefined){
                        Datarow=(Number(curpage)-1)*Number(pagelist)+rowIndex;//当前表格行对应在数据集中的行
                      }
                      DataSet[Datarow][TCombo.setfield[key]]=comboDataSet[comboTRrowindex][key];//TCombo.setfield[key]-主表字段
                      var mtableindex=-1;//dzmc对应在主表中的列索引默认为第1列,如果在固定列和非固定列中都有key值则以固定列为准
                      for(var i=0;i<that.options.Columns.length;i++){//先在非固定列中查找key对应的列
                        if (that.options.Columns[i]["field"]==TCombo.setfield[key]){
                          mtableindex=i;//dzmc对应在主表中的列索引
                          var TR=$('#'+that.id).find('tr');
                          break;
                        }
                      }
                      if(that.options.FixedColumns.length>0){//主表有固定列,再在固定列中查找key对应的列
                        for(var i=0;i<that.options.FixedColumns.length;i++){
                          if (that.options.FixedColumns[i]["field"]==TCombo.setfield[key]){
                            mtableindex=i;//dzmc对应在主表中的列索引
                            var TR=$('#'+that.id+'_fixed').find('tr');
                            break;
                          }
                        }
                      }
                      if (mtableindex!==-1){//在主表有相应的字段索引
                        that.SetCellData(TR,rowIndex,mtableindex,DataSet[Datarow][TCombo.setfield[key]]); //设置主表对应值
                        //var mTDnode=TR[rowIndex]["cells"][mtableindex];//主表对应的TDnode
                        //that.UpdateData(mTDnode,rowIndex,DataSet,DataSet[Datarow][TCombo.setfield[key]]);//更新数据集
                      }
                    } 
                  }
                }
              }
              var pagelist=$("#"+that.id+"_pagelist").val();
              var curpage=$("#"+that.id+"_curpage").val();
              var pageinfo={"pagelist":pagelist,"curpage":curpage};
              if (valChange){
                that.UpdateData(TDnode,rowIndex,mColumns,DataSet,newvalue);//更新数据集 
                that.options.OnCellEdit(TDnode,rowIndex,Field,DataSet,newvalue,pageinfo);
              }
              that.CheckExpression(TDnode,DataSet);
              that.options.OnComboClick(this,Field,$(this)[0].attributes[1].value,rowIndex,comboTRrowindex,$(this)[0].cellIndex,comboDataSet,DataSet,pageinfo); 
              $('#combo_'+Field+'bg').remove();
            });
          },210);
          $(TDnode).find("input").blur(function (event) {//失去焦点时
            var Value = $(this).val();
            if (oldvalue !== Value) {
              that.UpdateData(TDnode,rowIndex,mColumns,DataSet,Value);//更新数据集
            };
            $(TDnode).html(Value);
            that.CheckExpression(TDnode,DataSet);
            var pagelist=$("#"+that.id+"_pagelist").val();
            var curpage=$("#"+that.id+"_curpage").val();
            var pageinfo={"pagelist":pagelist,"curpage":curpage};
            that.options.OnCellEdit(TDnode,rowIndex,Field,DataSet,Value,pageinfo);
            setTimeout(function(){//延时.在没有想到input失去焦点时在不影响下拉列表单击改变单元格数据
              $('#combo_'+Field+'bg').remove();
            },210);
          }).val(oldvalue).focus(function(){//有焦点时
            
          }).select();
          
          $("input[name=td]").click(function(event){//输入框单击时
            event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
          });
          $("input[name=td]").dblclick(function(event){//输入框双击时
            event.stopPropagation();//调用停止冒泡的事件方法,否则cellData值会是html
          });
        },
        RefreshData:function(DataSet){//刷新当前页表格数据
          var that=this;
          var curpage=$("#"+this.id+"_curpage").val();//当前页
          var pagerecords=$("#"+this.id+"_pagelist").val();//页面显示记录条数
          /*var DataSet={};//数据集
          $.getJSON(this.options.Dataurl+"?ran="+Math.random(),function(data){
            DataSet=data["data"];
          });*/
          var totalrecords=DataSet.length;//总记录条数
          var FColnums=this.options.FixedColumns.length;//固定列数
          var Fstep=0;
          var Colnums=this.options.Columns.length;//不固定列数
          var TR=$('#'+that.id).find('tbody >tr');
          var TRrows=TR.length;
          if (FColnums>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            if (that.options.CheckBox){
              Fstep=1;  
            }
            if(curpage==undefined || pagerecords==undefined){
              curpage=1;
              pagerecords=totalrecords;
            }else{
              Number(totalrecords)<Number(pagerecords)?pagerecords=totalrecords:pagerecords=$("#"+that.id+"_pagelist").val();  
            }                     
            for (var i=0;i<pagerecords;i++){//从第一行开始-索引号为0
              if (FTR[i].style.display==""){              
                for (var j=0;j<FColnums+Fstep;j++){//从第一列开始-索引号为0
                  if (that.GetCellAttr(FTR,i,j,"type")=="data"){
                    var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                    if(that.options.FixedColumns[j-Fstep]["parentfield"]!==undefined){
                      that.SetCellData(FTR,i,j,DataSet[datarowindex][that.options.FixedColumns[j]["parentfield"]][that.GetCellAttr(FTR,i,j,"field")]);  
                    }else{
                      that.SetCellData(FTR,i,j,DataSet[datarowindex][that.GetCellAttr(FTR,i,j,"field")]);
                    }  
                  }  
                }
                for (var j=0;j<Colnums;j++){//从第一列开始-索引号为0
                  if (that.GetCellAttr(TR,i,j,"type")=="data"){
                    var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                    if(that.options.Columns[j]["parentfield"]!==undefined){
                      that.SetCellData(TR,i,j,DataSet[datarowindex][that.options.Columns[j]["parentfield"]][that.GetCellAttr(TR,i,j,"field")]);  
                    }else{
                      that.SetCellData(TR,i,j,DataSet[datarowindex][that.GetCellAttr(TR,i,j,"field")]);
                    }  
                  }  
                }
              }    
            } 
          }else{//如果没有固定列
            if(curpage==undefined || pagerecords==undefined){
              curpage=1;
              pagerecords=totalrecords;
            }else{
              Number(totalrecords)<Number(pagerecords)?pagerecords=totalrecords:pagerecords=$("#"+that.id+"_pagelist").val();  
            }                      
            for (var i=0;i<pagerecords;i++){//从第一行开始-索引号为0
              if (TR[i].style.display==""){              
                for (var j=0;j<Colnums;j++){//从第一列开始-索引号为0
                  if (that.GetCellAttr(TR,i,j,"type")=="data"){
                    var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                    if(that.options.Columns[j]["parentfield"]!==undefined){
                      that.SetCellData(TR,i,j,DataSet[datarowindex][that.options.Columns[j]["parentfield"]][that.GetCellAttr(TR,i,j,"field")]);  
                    }else{
                      that.SetCellData(TR,i,j,DataSet[datarowindex][that.GetCellAttr(TR,i,j,"field")]);
                    }  
                  }  
                }
              }    
            }
          }
          /*
          for(var i=0;i<TRrows;i++){
            if ($('input[name="'+that.id+'_checkList"]')[i].checked){                  
              selecteddatarow.push(i);
              if($("#"+that.id+"_pagetotal").html()!==undefined){
                $("#"+that.id+"_pagetotal").html(Number($("#"+that.id+"_pagetotal").html())-1);
              }
              $('input[name="'+that.id+'_checkList"]')[i].checked=false;
              TR.removeClass("selectedRow");
              FTR.removeClass("selectedRow");
              if(i%2 ==0){
                TR.addClass('evenRow');
                FTR.addClass('evenRow');
              }else{
                TR.addClass('oddRow');
                FTR.addClass('oddRow');
              }
              check=true; 
            }
          }
          */ 
        },
        GetCellData:function(TR,rowIndex,colIndex){//取单元格数据-TR-trnode;rowIndex-行索引;colIndex-列索引
          return TR[rowIndex]["cells"][colIndex]["innerText"]; 
        },
        GetCellAttr:function(TR,rowIndex,colIndex,attrName){//取单元格属性值-TR-trnode;rowIndex-行索引;colIndex-列索引;attrname-属性名称
          return TR[rowIndex]["cells"][colIndex]["attributes"][attrName]["value"];
        },
        SetCellData:function(TR,rowIndex,colIndex,Data){//设置单元格数据-TR-trnode;rowIndex-行索引;colIndex-列索引;Data-单元格数据
          TR[rowIndex]["cells"][colIndex]["innerHTML"]="";
          TR[rowIndex]["cells"][colIndex]["innerHTML"]=Data;
        },
        GetRowData:function (TD,DataSet){//取当前行数据
          var that=this;
          var rowData = {};
          var CTR=$(TD).parent();//当前行Node
          var rowIndex=CTR[0].rowIndex;//当前行索引
          var TR=$('#'+that.id).find('tbody >tr');//不固定Node
          var ColstartIndex=0;//默认不固定列开始索引号
          var ColendIndex=that.options.Columns.length;//默认不固定列结束索引号
          if (that.options.FixedColumns.length>0){//如果有固定列
            var FTR=$('#'+that.id+'_fixed').find('tbody >tr');
            var FColstartIndex=0;//默认固定列开始索引号
            var FColendIndex=that.options.FixedColumns.length;//默认固定列结束索引号
            if (that.options.CheckBox){
              FColstartIndex=1;
              FColendIndex=FColendIndex+1;  
            }
            for (var i=FColstartIndex;i<FColendIndex;i++){
              var field=FTR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var value=that.GetCellData(FTR,rowIndex,i);//单元格的文本
                rowData[field] = value;
              }
            }
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var value=that.GetCellData(TR,rowIndex,i);//单元格的文本
                rowData[field] = value;
              }
            }
            if(that.options.AttachColumns.length>0){//隐藏列信息
              for(var i=0;i<that.options.AttachColumns.length;i++){
                rowData[that.options.AttachColumns[i]["field"]]=DataSet[rowIndex][that.options.AttachColumns[i]["field"]];
              }
            }
            
          }else{//如果没有固定列
            for (var i=ColstartIndex;i<ColendIndex;i++){
              var field=TR[rowIndex]["cells"][i]["attributes"]["field"]["value"];//单元格字段
              if(field){
                var value=that.GetCellData(TR,rowIndex,i);//单元格的文本
                rowData[field] = value;
              }
            }
            if(that.options.AttachColumns.length>0){//隐藏列信息
              for(var i=0;i<that.options.AttachColumns.length;i++){
                rowData[that.options.AttachColumns[i]["field"]]=DataSet[rowIndex][that.options.AttachColumns[i]["field"]];
              }
            }
          }
          return rowData; 
        },
        LastPage:function(yushu){//最后一页处理-yushu-数据最后一页的行数
          var that=this;
          var curpage=$("#"+this.id+"_curpage").val();//当前页
          var pagerecords=$("#"+this.id+"_pagelist").val();//页面显示记录条数
          var FColnums=this.options.FixedColumns.length;//固定列数
          var FColstartIndex=0;//默认固定列开始索引号
          var FColendIndex=FColnums;//默认固定列结束索引号
          var Colnums=this.options.Columns.length;//不固定列数
          var ColstartIndex=0;//默认不固定列开始索引号
          var ColendIndex=Colnums;//默认不固定列结束索引号
          var TR=$('#'+this.id).find('tbody >tr');
          if(Number($("#"+this.id+"_curpage").val())>Number($("#"+this.id+"_totalpages").text())){$("#"+this.id+"_curpage").val($("#"+this.id+"_totalpages").text());}
          if ($("#"+this.id+"_curpage").val()==$("#"+this.id+"_totalpages").text() || curpage==undefined || pagerecords==undefined){//如果最后一页 
            if (yushu<TR.length && yushu!=0){
              if (FColnums>0){//如果有固定列
                var FTR=$('#'+this.id+'_fixed').find('tbody >tr');
                if (that.options.CheckBox){
                  FColstartIndex=1;
                  FColendIndex=Number(FColnums)+1;  
                }
                for (var i=yushu;i<TR.length;i++){
                  FTR[i].style.display="none";
                  TR[i].style.display="none"; 
                  for (var j=FColstartIndex;j<FColendIndex;j++){//从第一列开始-索引号为0
                    if (that.GetCellAttr(FTR,i,j,"type")=="data"){
                      var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                      that.SetCellData(FTR,i,j,"");  
                    }  
                  }
                  for (var j=ColstartIndex;j<ColendIndex;j++){//从第一列开始-索引号为0
                    if (that.GetCellAttr(TR,i,j,"type")=="data"){
                      var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                      that.SetCellData(TR,i,j,"");  
                    }  
                  }    
                }
              }else{//没有固定列
                if (that.options.CheckBox){
                  var FTR=$('#'+this.id+'_fixed').find('tbody >tr');  
                }
                for (var i=yushu;i<TR.length;i++){
                  if (that.options.CheckBox){
                    FTR[i].style.display="none";
                  }
                  TR[i].style.display="none"; 
                  for (var j=ColstartIndex;j<ColendIndex;j++){//从第一列开始-索引号为0
                    if (that.GetCellAttr(TR,i,j,"type")=="data"){
                      var datarowindex=Number(pagerecords)*(Number(curpage)-1)+i;
                      that.SetCellData(TR,i,j,"");  
                    }  
                  }    
                }
              }
            }else{
              console.log(yushu);
              if (this.options.CheckBox || FColnums>0){//如果有固定列或checkbox
                var FTR=$('#'+this.id+'_fixed').find('tbody >tr');
                for (var i=0;i<TR.length;i++){
                  FTR[i].style.display="";    
                }
              }
              for (var i=0;i<TR.length;i++){
                TR[i].style.display="";  
              }
            }
            $("#"+this.id+"_pagestart").html(Number(pagerecords)*(Number(curpage)-1)+1);
            $("#"+this.id+"_pageend").html($("#"+this.id+"_pagetotal").html()); 
          }else{
            if (this.options.CheckBox || FColnums>0){//如果有固定列或checkbox
              var FTR=$('#'+this.id+'_fixed').find('tbody >tr');
              for (var i=0;i<TR.length;i++){
                FTR[i].style.display="";    
              }
            }
            for (var i=0;i<TR.length;i++){
              TR[i].style.display="";  
            }
            $("#"+this.id+"_pagestart").html(Number(pagerecords)*(Number(curpage)-1)+1);
            $("#"+this.id+"_pageend").html(Number($("#"+this.id+"_pagestart").html())+Number(pagerecords)-1);  
          }  
        },
        /***************************
        /* 获取选择的行数组
        /***************************/
        SelectedRow:function(){
          if (this.options.CheckBox){
            var FTR=$('#'+this.id+'_fixed').find('tbody >tr');
            var FTRrows=FTR.length;
            var selecteddatarow=[];
            for(var i=0;i<FTRrows;i++){
              if ($('input[name="'+this.id+'_checkList"]')[i].checked){                  
                selecteddatarow.push(i); 
              }
            }
            return selecteddatarow;
          }    
        },
        /**********messagebox***********
        * string-显示提示字符串(默认)
        * strhtml-html
        * Msgwidth-消息框宽度
        * Msgheight-消息框高度
        ******************************/ 
        MsgBox:function(Msgwidth,Msgheight,string,strhtml){
          var winSize = function(){
            var xScroll, yScroll, windowWidth, windowHeight, pageWidth, pageHeight;
            // innerHeight获取的是可视窗口的高度，IE不支持此属性
            if (window.innerHeight && window.scrollMaxY) {
              xScroll = document.body.scrollWidth;
              yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
              xScroll = document.body.scrollWidth;
              yScroll = document.body.scrollHeight;
            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
              xScroll = document.body.offsetWidth;
              yScroll = document.body.offsetHeight;
            }
            if (self.innerHeight) {    // all except Explorer
              windowWidth = self.innerWidth;
              windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
              windowWidth = document.documentElement.clientWidth;
              windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
              windowWidth = document.body.clientWidth;
              windowHeight = document.body.clientHeight;
            }
            // for small pages with total height less then height of the viewport
            if (yScroll < windowHeight) {
              pageHeight = windowHeight;
            } else {
              pageHeight = yScroll;
            }
            // for small pages with total width less then width of the viewport
            if (xScroll < windowWidth) {
              pageWidth = windowWidth;
            } else {
              pageWidth = xScroll;
            }
            return{
              'pageWidth':pageWidth,
              'pageHeight':pageHeight,
              'windowWidth':windowWidth,
              'windowHeight':windowHeight
            }
          }();
          var MsgBox = document.createElement("div");
          MsgBox.id="MsgBox";
          MsgBox.style.position = "absolute";
          MsgBox.style.width = Msgwidth+"px";
          MsgBox.style.height = Msgheight+"px";
          MsgBox.style.left = (winSize.windowWidth-Msgwidth)/2+"px";
          MsgBox.style.top = (winSize.windowHeight-Msgheight)/2-50+"px";
          MsgBox.style.textAlign = "center";
          MsgBox.style.zIndex = "320"; 
          //遮罩层
          var shadowDiv = document.createElement('div'); //添加阴影DIV
          shadowDiv.id = "shadowDiv";
          shadowDiv.style.position = "absolute";
          shadowDiv.style.top = "0";
          shadowDiv.style.left = "0";
          shadowDiv.style.background = "#000000";
          shadowDiv.style.width = winSize.windowWidth+"px";
          shadowDiv.style.height = winSize.windowHeight + 30+"px";
          shadowDiv.style.zIndex = "310";
          shadowDiv.style.opacity = "0.5";
          if (string==""){
            var strHtml=strhtml;
            MsgBox.innerHTML = strHtml;
            document.body.appendChild(MsgBox);
            document.body.appendChild(shadowDiv);  
          }else{
            var strHtml = '<ul style="list-style:none;margin:0px;padding:0px;width:100%">\n';
            strHtml += '<li style="background:#0b6ed2;text-align:left;padding-left:10px;font-size:14px;font-weight:bold;line-height:35px;border:1px solid #0b6ed2;color:white">提示</li>';
            strHtml += '<li style="background:#E9E9E9;text-align:left;font-size:12px;height:95px;border-left:1px solid #0b6ed2;border-right:1px solid #0b6ed2;color:#060476"><div class="msginfo"><div class="msgcontent" style="margin-left:64px;text-align:left;width:200px;">'+string+'</div></div></li>';
            strHtml += '<li style="background:#0b6ed2;text-align:center;font-weight:bold;height:30px;line-height:25px;border-left:1px solid #0b6ed2;border-right:1px solid #0b6ed2;border-bottom:1px solid #0b6ed2;"><input id="confirm" type="button" value="确 定" style="width:80px;background:#CDCDCD;color:#000;border:0px solid white;font-size:14px;line-height:20px;outline:none;margin:2px 0 0 0;"/></li>';
            strHtml += '</ul>'; 
            MsgBox.innerHTML = strHtml;
            document.body.appendChild(MsgBox);
            document.body.appendChild(shadowDiv);
            var margintop=($('.msginfo')[0].clientHeight-$('.msgcontent')[0].clientHeight)/2
            $('.msgcontent').css("margin-top",margintop+"px");
            $('#confirm').on('click',function(){ 
              MsgBox.remove();
              shadowDiv.remove();
            });
            $('#cancel').on('click',function(){ 
              MsgBox.remove();
              shadowDiv.remove();
            });
          }
          MsgBox.focus();  
        },
        /*****************/
        /* DataSet-数据集
        /* Order-升序或降序
        /* Field-排序的字段    
       /*****************/
        SortData:function(DataSet,Order,Field){
          if(Number(DataSet[0][Field])!=="NaN") {//先判断该字段的第一个值是否为数字,!==NaN-表示是数字
            switch(Order){
              case "asc":
                 DataSet.sort(function(x, y) {return x[Field] - y[Field]}); 
              break;
              case "desc":
                 DataSet.sort(function(x, y) {return y[Field] - x[Field]});
              break;
            }
          }else if(Date(DataSet[0][Field])!=="NaN"){
            switch(Order){
              case "asc":
                 DataSet.sort(function(x, y) {return Date.parse(x[Field]) - Date.parse(y[Field])});
              break;
              case "desc":
                 DataSet.sort(function(x, y) {return Date.parse(y[Field]) - Date.parse(x[Field])});
              break;
            }
          }else{
            switch(Order){
              case "asc":
                 DataSet.sort(function(x, y) {return x[Field].localeCompare(y[Field])});
              break;
              case "desc":
                 DataSet.sort(function(x, y) {return y[Field].localeCompare(x[Field])});
              break;
            }
          } 
          return DataSet;
        } 
             
      };
      return new microtable(this, options);
    };
    /**(json)数组查询扩展(无须依赖jQuery)***
    *
    ***********************/
    Array.prototype.QueryData = function (express) {
      var rs = [];
      for (var index in this) {
        var DataSet = this[index];
        if (typeof (this[index]) != 'function'){
          if (eval(express)) {
            rs.push(DataSet);
          }
        }
      }
      return rs;
    };
    /**(json)数组查询扩展(依赖jQuery)***
    *
    ***********************/
    //Array.prototype.query = function (s) { return eval("(jQuery.grep(this, function (field, index){return " + s + ";}))"); };
    Array.prototype.contains = function ( needle ) {
      for (i in this) {
        if (this[i] == needle) return true;
      }
      return false;
    };
})(jQuery,window,document);
/**********************
*miccombogrid 0.2.11
*
**********************/
;(function($,window,document,undefined){
    "use strict";
    $.fn.miccombogrid = function(options){
      var miccombogrid = function(ele, opt){
        this.element = ele,
        this.defaults = {
          "Showtitle":true,
          "Datamethod":"local",//可以是本地local也可以是远程remote,text-自定义文本
          "Dataurl":"",
          "height":"120",
          "blankbreak":true,//设置有空格就停止
          "columns":[],//下拉列表的列数据
          "getfield":"",//当前单元格对应下拉列表的字段
          "setfield":{}
        }
        this.options = $.extend({},this.defaults,opt),
        this.combogrid=$(this.element[0]), 
        this.id=this.element[0].id,//本表格的id    
        this.combogridinit()
      }
      miccombogrid.prototype={//定义表格的方法
        combogridinit:function(){//初始化表格
          if($('#combogrid_bg').length!==0){
            $('#combogrid_bg').remove();
          }
          var that=this;
          var OP=this.options;
          //var oldvalue=$("#"+this.id).val();
          var colNum=OP.columns.length;//下拉列表列数
          var rowNum=[];//下拉列表的值(数组)的个数(行数)-自定义值时使用
          var rowNums=0;
          var comboTable='<div id="combogrid_bg"  style="position:absolute;top:'+parseInt($("#"+OP.id).offset().top+18)+'px;left:'+$("#"+OP.id).offset().left+'px;z-index:301;border:1px solid #8F8BFB;background-color:#DBDBDB;" cellpadding="0" cellspacing="0">';
          if (OP.Showtitle){
            comboTable+='<div id="combogrid_header">';
              comboTable+='<table id="combogrid_head">';
                comboTable+='<thead>';
                  comboTable+='<tr>';
                  for (var i=0;i<colNum;i++){
                    if (OP.columns[i]["width"]!=="auto"){
                      comboTable+='<th class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;background-color:#DBDBDB;padding:2px;border:1px solid #C5C5C5;border-bottom:0px solid #C5C5C5;cursor:default;width:'+OP.columns[i]["width"]+'px;max-width:'+OP.columns[i]["width"]+'px;">';
                    }else{
                      comboTable+='<th class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;background-color:#DBDBDB;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+=OP.columns[i].title;//下拉列表标题
                    comboTable+='</th>';
                  }
                  comboTable+='<tr>';
                comboTable+='</thead>';
              comboTable+='</table>';
            comboTable+='</div>';
          }
            comboTable+='<div id="combogrid_bodier" style="max-height:'+OP["height"]+'px;overflow:auto;border-top: 1px solid #C5C5C5;border-bottom: 1px solid #C5C5C5;border-right: 1px solid #C5C5C5;">';
              comboTable+='<table id="combogrid_body">';
              comboTable+='<tbody>';
          switch(OP.Datamethod){
            case "text":
              for(var i=0;i<colNum;i++){
                rowNum[i]=OP.columns[i].value.length;//下拉列表的值(数组)的个数(行数)  
              }
              rowNums=Math.max.apply(null,rowNum);
            break;
            case "local":
              var getfieldindex=0;////当前单元格对应下拉列表的字段的索引
              for(var i=0;i<colNum;i++){
                if (OP.columns[i]["field"]==OP.getfield){
                  getfieldindex=i;
                  break;
                }
              }
              var comboDataSet=[]; 
              $.ajaxSettings.async = false;
              $.getJSON(OP.Dataurl+"?ran="+Math.random(),function(data){//读取数据库文件
                comboDataSet=data['data'];
                if(OP.queryfieldvalue!=undefined){//如果有要查询的字段
                  comboDataSet=[];
                  var qexpress="";
                  var prekey="";
                  for(var i=0;i<OP.queryfieldvalue.length;i++){
                    for (var key in OP.queryfieldvalue[i]) {
                      if(prekey==""){
                        if(i==OP.queryfieldvalue.length-1){
                          qexpress+='item["'+key+'"]'+OP.queryfieldvalue[i][key]+'';
                        }else{
                          qexpress+='(item["'+key+'"]'+OP.queryfieldvalue[i][key];
                        }
                        prekey=key;
                        break; 
                      }else{
                        if(i==OP.queryfieldvalue.length-1){
                          qexpress+=' item["'+key+'"]'+OP.queryfieldvalue[i][key]+')';  
                        }else{
                          qexpress+='item["'+key+'"]'+OP.queryfieldvalue[i][key]; 
                        }
                        prekey=key;
                        break;
                      }
                    }                     
                  }
                  comboDataSet=data['data'].filter(function(item){
                    return eval(qexpress);
                  });
                } 
              });
              $.ajaxSettings.async = true;
              rowNums=comboDataSet.length;
            break;
            case "remote":
              var getfieldindex=0;////当前单元格对应下拉列表的字段的索引
              for(var i=0;i<colNum;i++){
                if (OP.columns[i]["field"]==OP.getfield){
                  getfieldindex=i;
                  break;
                }
              }
              var comboDataSet=[]; 
              $.ajaxSettings.async = false;
              $.getJSON(OP.Dataurl+"?ran="+Math.random(),function(data){//remote读取数据库文件
                comboDataSet=data['data'];
              });
              $.ajaxSettings.async = true;
              rowNums=comboDataSet.length;
            break;
          }
          for(var i=0;i<rowNums;i++){
            comboTable+='<tr>';
            if(comboDataSet!==undefined){
              if(OP.blankbreak && (comboDataSet[i][OP.getfield].replace(/\s+/g,"")=="" || OP.getfield==undefined)){break;}
            }
            for(var j=0;j<colNum;j++){
              switch(OP.Datamethod){
                case "text":
                  if(OP.columns[j].value[i]!=undefined){
                    if (OP.columns[j]["width"]!=="auto"){
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+OP.columns[j]["width"]+'px;">';
                    }else{
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+=OP.columns[j].value[i];
                    comboTable+='</td>';
                  }else{
                    if (OP.columns[j]["width"]!=="auto"){
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+OP.columns[j]["width"]+'px;">';
                    }else{
                      comboTable+='<td class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;cursor:default;">';
                    }
                      comboTable+='';
                    comboTable+='</td>';
                  }
                break;
                case "local":
                  comboTable+='<td type="data" field="'+OP.columns[j]["field"]+'" class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+OP.columns[j]["width"]+'px;max-width:'+OP.columns[j]["width"]+'px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">';
                    comboTable+=comboDataSet[i][OP.columns[j]["field"]]; 
                  comboTable+='</td>';
                break;
                case "remote":
                  comboTable+='<td type="data" field="'+OP.columns[j]["field"]+'" class="align-center align-middle" rowspan="1" colspan="1" style="font-size:9pt;padding:2px;border:1px solid #C5C5C5;border-top:0px solid #C5C5C5;cursor:default;width:'+OP.columns[j]["width"]+'px;max-width:'+OP.columns[j]["width"]+'px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">';
                    comboTable+=comboDataSet[i][OP.columns[j]["field"]];
                  comboTable+='</td>';
                break;
              }
            } 
            comboTable+='<tr>';  
          }   
                comboTable+='<tbody>';
              comboTable+='</table>';
            comboTable+='</div>';
          comboTable+='</div>';
          $('body').append(comboTable); 
          $('#combogrid_body').find("tbody:empty").remove();
          $('#combogrid_head').find("thead >tr:empty").remove();
          $('#combogrid_body').find("tbody >tr:empty").remove();
          $('#combogrid_body').find("tbody >tr:odd").addClass('oddRow');
          $('#combogrid_body').find("tbody >tr:even").addClass('evenRow'); 
          var comboTR=$('#combogrid_body').find("tr");
          var comboTD=$('#combogrid_body').find("td");
          for(var i=0;i<rowNums;i++){
            if(comboDataSet!==undefined){
              if(OP.blankbreak && (comboDataSet[i][OP.getfield].replace(/\s+/g,"")=="" || OP.getfield==undefined)){break;}
            }
            switch(OP.Datamethod){
              case "text":
                if($("#"+OP.id).val()==that.GetCellData(comboTR,i,OP.getcolval)){
                  comboTR.eq(i).removeClass();
                  comboTR.eq(i).addClass('selectedRow');
                }
              break;
              case "local": 
                if($("#"+OP.id).val()==that.GetCellData(comboTR,i,getfieldindex)){
                  comboTR.eq(i).removeClass();
                  comboTR.eq(i).addClass('selectedRow');
                  //滚动到当前行
                  
                }
              break;
              case "remote": 
                if($("#"+OP.id).val()==that.GetCellData(comboTR,i,getfieldindex)){
                  comboTR.eq(i).removeClass();
                  comboTR.eq(i).addClass('selectedRow');
                  //滚动到当前行
                  
                  console.log(comboTR.eq(i)[0].offsetTop);
                }
              break;
            }
          }
          comboTR.on('mouseover',function(){//表格鼠标滑过行
            var rowindex=this.rowIndex;
            if($(this).attr("class")!=="selectedRow"){
              $(this).attr({"class":""});
              $(this).addClass("overRow");
            }
          });
          comboTR.on('mouseout',function(){//列表格鼠标滑出行
            var rowindex=this.rowIndex; 
            if($(this).attr("class")!=="selectedRow"){
              $(this).removeClass("overRow");
              if(rowindex%2 ==0){
                $(this).addClass('evenRow');
              }else{
                $(this).addClass('oddRow');
              }
            }
          });
          comboTD.click(function (event) {//单击时              
            var comboTRrowindex=$(this).parent()[0].rowIndex;
            var newvalue="";
            switch(OP.Datamethod){
              case "text": 
                newvalue = $(this).parent()[0]["cells"][OP.getcolval].innerHTML;
              break;
              case "local":
                newvalue = $(this).parent()[0]["cells"][getfieldindex].innerHTML;
              break;
              case "remote":
                newvalue = $(this).parent()[0]["cells"][getfieldindex].innerHTML;
              break;
            }
            $("#"+OP.id).val(newvalue); 
            $('#combogrid_bg').remove();
            $("#"+OP.id).focus();
          });
          $("#"+OP.id).blur(function (event) {//失去焦点时
            setTimeout(function(){//延时.在没有想到input失去焦点时在不影响下拉列表单击改变单元格数据
              $('#combogrid_bg').remove();
            },200);
          }).focus();
          //console.log(oldvalue);
        },
        GetCellData:function(TR,rowIndex,colIndex){//取单元格数据-TR-trnode;rowIndex-行索引;colIndex-列索引
          return TR[rowIndex]["cells"][colIndex]["innerText"]; 
        }
      }
      return new miccombogrid(this, options);
    }
})(jQuery,window,document);
/*****************************************/
/* datetimepicker
/*****************************************/
(function( $ ) {
	'use strict';
	var default_options  = {
		i18n:{
			ru:{ // Russian
				months:[
					'Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'
				],
				dayOfWeek:[
					"Вск", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
				]
			},
			en:{ // English
				months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
				],
				dayOfWeek: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
				]
			},
			de:{ // German
				months:[
					'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'
				],
				dayOfWeek:[
					"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
				]
			},
			nl:{ // Dutch
				months:[
					"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
				],
				dayOfWeek:[
					"zo", "ma", "di", "wo", "do", "vr", "za"
				]
			},
			tr:{ // Turkish
				months:[
					"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
				],
				dayOfWeek:[
					"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
				]
			},
			fr:{ //French
				months:[
			    "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
				],
				dayOfWeek:[
					"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
				]
			},
			es:{ // Spanish
				months: [
					"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
				],
				dayOfWeek: [
					"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
				]
			},
			th:{ // Thai
				months:[
					'มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'
				],
				dayOfWeek:[
					'อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'
				]
			},
			pl:{ // Polish
				months: [
					"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
				],
				dayOfWeek: [
					"nd", "pn", "wt", "śr", "cz", "pt", "sb"
				]
			},
			pt:{ // Portuguese
				months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
				],
				dayOfWeek: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
				]
			},
			ch:{ // Simplified Chinese
				months: [
					"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"
				],
				dayOfWeek: [
					"日", "一","二","三","四","五","六"
				]
			},
			se:{ // Swedish
				months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September","Oktober", "November", "December"
				],
				dayOfWeek: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
				]
			},
			kr:{ // Korean
				months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
				],
				dayOfWeek: ["일", "월", "화", "수", "목", "금", "토"
				]
			},
			it:{ // Italian
				months: [
					"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
				],
				dayOfWeek: [
					"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
				]
			}
		},
		value:'',
		lang:'en',
		format:'Y/m/d H:i',
		formatTime:'H:i',
		formatDate:'Y/m/d',
		step:60,
		closeOnDateSelect:0,
		closeOnWithoutClick:true,
		timepicker:true,
		datepicker:true,
		minDate:false,
		maxDate:false,
		minTime:false,
		maxTime:false,
		allowTimes:[],
		opened:false,
		inline:false,
		onSelectDate:function() {},
		onSelectTime:function() {},
		onChangeMonth:function() {},
		onChangeDateTime:function() {},
		onShow:function() {},
		onClose:function() {},
		onGenerate:function() {},
		withoutCopyright:true,
		inverseButton:false,
		hours12:false,
		next:'mitsoft_next',
		prev : 'mitsoft_prev',
		dayOfWeekStart:0,
		timeHeightInTimePicker:25,
		timepickerScrollbar:true,
		todayButton:true, // 2.1.0
		defaultSelect:true, // 2.1.0
		scrollMonth:true,
		scrollTime:true,
		scrollInput:true,
		mask:false,
		validateOnBlur:true,
		allowBlank:false,
		yearStart:2000,
		yearEnd:2100,
		style:'',
		id:'',
		roundTime:'round', //ceil, floor
		className:'',
		weekends:[],
		yearOffset:0
	};
	// fix for ie8
	if ( !Array.prototype.indexOf ) {
		Array.prototype.indexOf = function(obj, start) {
			 for (var i = (start || 0), j = this.length; i < j; i++) {
				 if (this[i] === obj) { return i; }
			 }
			 return -1;
		}
	};
	$.fn.mitsoftScroller = function( _percent ) {
		return this.each(function() {
			var timeboxparent = $(this);
			if( !$(this).hasClass('mitsoft_scroller_box') ) {
				var pointerEventToXY = function( e ) {
						var out = {x:0, y:0};
						if( e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel' ) {
							var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
							out.x = touch.pageX;
							out.y = touch.pageY;
						}else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
							out.x = e.pageX;
							out.y = e.pageY;
						}
						return out;
					},
        move = 0,
        timebox = timeboxparent.children().eq(0),
        parentHeight = timeboxparent[0].clientHeight,
        height = timebox[0].offsetHeight,
        scrollbar = $('<div class="mitsoft_scrollbar"></div>'),
        scroller = $('<div class="mitsoft_scroller"></div>'),
        maximumOffset = 100,
        start = false;
				scrollbar.append(scroller);
				timeboxparent.addClass('mitsoft_scroller_box').append(scrollbar);
				scroller.on('mousedown.mitsoft_scroller',function ( event ) {
					if( !parentHeight )
						timeboxparent.trigger('resize_scroll.mitsoft_scroller',[_percent]);
					var pageY = event.pageY,
						top = parseInt(scroller.css('margin-top')),
						h1 = scrollbar[0].offsetHeight;
					$(document.body).addClass('mitsoft_noselect');
					$([document.body,window]).on('mouseup.mitsoft_scroller',function arguments_callee() {
						$([document.body,window]).off('mouseup.mitsoft_scroller',arguments_callee)
							.off('mousemove.mitsoft_scroller',move)
							.removeClass('mitsoft_noselect');
					});
					$(document.body).on('mousemove.mitsoft_scroller',move = function(event) {
						var offset = event.pageY-pageY+top;
						if( offset<0 )
							offset = 0;
						if( offset+scroller[0].offsetHeight>h1 )
							offset = h1-scroller[0].offsetHeight;
						timeboxparent.trigger('scroll_element.mitsoft_scroller',[maximumOffset?offset/maximumOffset:0]);
					});
				});

				timeboxparent
					.on('scroll_element.mitsoft_scroller',function( event,percent ) {
						if( !parentHeight )
							timeboxparent.trigger('resize_scroll.mitsoft_scroller',[percent,true]);
						percent = percent>1?1:(percent<0||isNaN(percent))?0:percent;
						scroller.css('margin-top',maximumOffset*percent);
						timebox.css('marginTop',-parseInt((height-parentHeight)*percent))
					})
					.on('resize_scroll.mitsoft_scroller',function( event,_percent,noTriggerScroll ) {
						parentHeight = timeboxparent[0].clientHeight;
						height = timebox[0].offsetHeight;
						var percent = parentHeight/height,
							sh = percent*scrollbar[0].offsetHeight;
						if( percent>1 )
							scroller.hide();
						else{
							scroller.show();
							scroller.css('height',parseInt(sh>10?sh:10));
							maximumOffset = scrollbar[0].offsetHeight-scroller[0].offsetHeight;
							if( noTriggerScroll!==true )
								timeboxparent.trigger('scroll_element.mitsoft_scroller',[_percent?_percent:Math.abs(parseInt(timebox.css('marginTop')))/(height-parentHeight)]);
						}
					});
				timeboxparent.mousewheel&&timeboxparent.mousewheel(function(event, delta, deltaX, deltaY) {
					var top = Math.abs(parseInt(timebox.css('marginTop')));
					timeboxparent.trigger('scroll_element.mitsoft_scroller',[(top-delta*20)/(height-parentHeight)]);
					event.stopPropagation();
					return false;
				});
				timeboxparent.on('touchstart',function( event ) {
					start = pointerEventToXY(event);
				});
				timeboxparent.on('touchmove',function( event ) {
					if( start ) {
						var coord = pointerEventToXY(event), top = Math.abs(parseInt(timebox.css('marginTop')));
						timeboxparent.trigger('scroll_element.mitsoft_scroller',[(top-(coord.y-start.y))/(height-parentHeight)]);
						event.stopPropagation();
						event.preventDefault();
					};
				});
				timeboxparent.on('touchend touchcancel',function( event ) {
					start = false;
				});
			}
			timeboxparent.trigger('resize_scroll.mitsoft_scroller',[_percent]);
		});
	};
	$.fn.datetimepicker = function( opt ) {
		var KEY0 = 48,
			KEY9 = 57,
			_KEY0 = 96,
			_KEY9 = 105,
			CTRLKEY = 17,
			DEL = 46,
			ENTER = 13,
			ESC = 27,
			BACKSPACE = 8,
			ARROWLEFT = 37,
			ARROWUP = 38,
			ARROWRIGHT = 39,
			ARROWDOWN = 40,
			TAB = 9,
			F5 = 116,
			AKEY = 65,
			CKEY = 67,
			VKEY = 86,
			ZKEY = 90,
			YKEY = 89,
			ctrlDown	=	false,
			options = ($.isPlainObject(opt)||!opt)?$.extend(true,{},default_options,opt):$.extend({},default_options),
			createDateTimePicker = function( input ) {
				var datetimepicker = $('<div '+(options.id?'id="'+options.id+'"':'')+' '+(options.style?'style="'+options.style+'"':'')+' class="mitsoft_datetimepicker mitsoft_noselect '+options.className+'"></div>'),
					mitsoft_copyright = $('<div class="mitsoft_copyright"><a target="_blank" href="http://mitsoft.net/jqplugins/datetimepicker/">mitsoft.net</a></div>'),
					datepicker = $('<div class="mitsoft_datepicker active"></div>'),
					mounth_picker = $('<div class="mitsoft_mounthpicker"><button type="button" class="mitsoft_prev"></button><button type="button" class="mitsoft_today_button"></button><div class="mitsoft_label mitsoft_month"><span></span></div><div class="mitsoft_label mitsoft_year"><span></span></div><button type="button" class="mitsoft_next"></button></div>'),
					calendar = $('<div class="mitsoft_calendar"></div>'),
					timepicker = $('<div class="mitsoft_timepicker active"><button type="button" class="mitsoft_prev"></button><div class="mitsoft_time_box"></div><button type="button" class="mitsoft_next"></button></div>'),
					timeboxparent = timepicker.find('.mitsoft_time_box').eq(0),
					timebox = $('<div class="mitsoft_time_variant"></div>'),
					scrollbar = $('<div class="mitsoft_scrollbar"></div>'),
					scroller = $('<div class="mitsoft_scroller"></div>'),
					monthselect =$('<div class="mitsoft_select mitsoft_monthselect"><div></div></div>'),
					yearselect =$('<div class="mitsoft_select mitsoft_yearselect"><div></div></div>');

				//constructor lego
				mounth_picker
					.find('.mitsoft_month span')
						.after(monthselect);
				mounth_picker
					.find('.mitsoft_year span')
						.after(yearselect);

				mounth_picker
					.find('.mitsoft_month,.mitsoft_year')
						.on('mousedown.mitsoft',function(event) {
							mounth_picker
								.find('.mitsoft_select')
									.hide();
							var select = $(this).find('.mitsoft_select').eq(0),
								val = 0,
								top = 0;

							if( _mitsoft_datetime.currentTime )
								val = _mitsoft_datetime.currentTime[$(this).hasClass('mitsoft_month')?'getMonth':'getFullYear']();

							select.show();
							for(var items = select.find('div.mitsoft_option'),i = 0;i<items.length;i++) {
								if( items.eq(i).data('value')==val ) {
									break;
								}else top+=items[0].offsetHeight;
							}

							select.mitsoftScroller(top/(select.children()[0].offsetHeight-(select[0].clientHeight)));
							event.stopPropagation();
							return false;
						});

				mounth_picker
					.find('.mitsoft_select')
						.mitsoftScroller()
						.on('mousedown.mitsoft',function( event ) {
							event.stopPropagation();
							event.preventDefault();
						})
						.on('mousedown.mitsoft','.mitsoft_option',function( event ) {
							if( _mitsoft_datetime&&_mitsoft_datetime.currentTime )
								_mitsoft_datetime.currentTime[$(this).parent().parent().hasClass('mitsoft_monthselect')?'setMonth':'setFullYear']($(this).data('value'));
							$(this).parent().parent().hide();
							datetimepicker.trigger('xchange.mitsoft');
							options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						});


				// set options
				datetimepicker.setOptions = function( _options ) {
					options = $.extend(true,{},options,_options);
					if( (options.open||options.opened)&&(!options.inline) ) {
						input.trigger('open.mitsoft');
					}

					if( options.inline ) {
						datetimepicker.addClass('mitsoft_inline');
						input.after(datetimepicker).hide();
						datetimepicker.trigger('afterOpen.mitsoft');
					}

					if( options.inverseButton ) {
						options.next = 'mitsoft_prev';
						options.prev = 'mitsoft_next';
					}

					if( options.datepicker )
						datepicker.addClass('active');
					else
						datepicker.removeClass('active');
						
					if( options.timepicker )
						timepicker.addClass('active');
					else
						timepicker.removeClass('active');

					if( options.value ){
						input&&input.val&&input.val(options.value);
						_mitsoft_datetime.setCurrentTime(options.value);
					}

					if( isNaN(options.dayOfWeekStart)||parseInt(options.dayOfWeekStart)<0||parseInt(options.dayOfWeekStart)>6 )
						options.dayOfWeekStart = 0;
					else
						options.dayOfWeekStart = parseInt(options.dayOfWeekStart);

					if( !options.timepickerScrollbar )
						scrollbar.hide();

					var tmpDate = [],timeOffset;
					if( options.minDate && ( tmpDate = /^-(.*)$/.exec(options.minDate) ) && (tmpDate=Date.parseDate(tmpDate[1], options.formatDate)) ) {
						timeOffset = tmpDate.getTime()+-1*(tmpDate.getTimezoneOffset())*60000;
						options.minDate = new Date((_mitsoft_datetime.now()).getTime()-timeOffset).dateFormat( options.formatDate );
					}
					if( options.maxDate && ( tmpDate = /^\+(.*)$/.exec(options.maxDate) ) && (tmpDate=Date.parseDate(tmpDate[1], options.formatDate)) ) {
						timeOffset = tmpDate.getTime()+-1*(tmpDate.getTimezoneOffset())*60000;
						options.maxDate = new Date((_mitsoft_datetime.now()).getTime()+timeOffset).dateFormat( options.formatDate );
					}

					mounth_picker
						.find('.mitsoft_today_button')
							.css('visibility',!options.todayButton?'hidden':'visible');

					if( options.mask ) {
						var e,
							getCaretPos = function ( input ) {
								try{
									if ( document.selection && document.selection.createRange ) {
										var range = document.selection.createRange();
										return range.getBookmark().charCodeAt(2) - 2;
									}else
										if ( input.setSelectionRange )
											return input.selectionStart;
								}catch(e) {
									return 0;
								}
							},
							setCaretPos = function ( node,pos ) {
								var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
								if(!node) {
									return false;
								}else if(node.createTextRange) {
									var textRange = node.createTextRange();
									textRange.collapse(true);
									textRange.moveEnd(pos);
									textRange.moveStart(pos);
									textRange.select();
									return true;
								}else if(node.setSelectionRange) {
									node.setSelectionRange(pos,pos);
									return true;
								}
								return false;
							},
							isValidValue = function ( mask,value ) {
								var reg = mask
									.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,'\\$1')
									.replace(/_/g,'{digit+}')
									.replace(/([0-9]{1})/g,'{digit$1}')
									.replace(/\{digit([0-9]{1})\}/g,'[0-$1_]{1}')
									.replace(/\{digit[\+]\}/g,'[0-9_]{1}');
								return RegExp(reg).test(value);
							};
						input.off('keydown.mitsoft');
						switch(true) {
							case ( options.mask===true ):
								//options.mask = (new Date()).dateFormat( options.format );
								//options.mask = options.mask.replace(/[0-9]/g,'_');
								options.mask = options.format
									.replace(/Y/g,'9999')
									.replace(/F/g,'9999')
									.replace(/m/g,'19')
									.replace(/d/g,'39')
									.replace(/H/g,'29')
									.replace(/i/g,'59')
									.replace(/s/g,'59');
							case ( $.type(options.mask) == 'string' ):
								if( !isValidValue( options.mask,input.val() ) )
									input.val(options.mask.replace(/[0-9]/g,'_'));

								input.on('keydown.mitsoft',function( event ) {
									var val = this.value,
										key = event.which;
									switch(true) {
										case (( key>=KEY0&&key<=KEY9 )||( key>=_KEY0&&key<=_KEY9 ))||(key==BACKSPACE||key==DEL):
											var pos = getCaretPos(this),
												digit = ( key!=BACKSPACE&&key!=DEL )?String.fromCharCode((_KEY0 <= key && key <= _KEY9)? key-KEY0 : key):'_';
											if( (key==BACKSPACE||key==DEL)&&pos ) {
												pos--;
												digit='_';
											}
											while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
												pos+=( key==BACKSPACE||key==DEL )?-1:1;

											val = val.substr(0,pos)+digit+val.substr(pos+1);
											if( $.trim(val)=='' )
												val = options.mask.replace(/[0-9]/g,'_');
											else
												if( pos==options.mask.length )
													break;

											pos+=(key==BACKSPACE||key==DEL)?0:1;
											while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
												pos+=(key==BACKSPACE||key==DEL)?-1:1;
											if( isValidValue( options.mask,val ) ) {
												this.value = val;
												setCaretPos(this,pos);
											}else if( $.trim(val)=='' )
												this.value = options.mask.replace(/[0-9]/g,'_');
											else{
												input.trigger('error_input.mitsoft');
											}
										break;
										case ( !!~([AKEY,CKEY,VKEY,ZKEY,YKEY].indexOf(key))&&ctrlDown ):
										 case !!~([ESC,ARROWUP,ARROWDOWN,ARROWLEFT,ARROWRIGHT,F5,CTRLKEY,TAB,ENTER].indexOf(key)):
										return true;
									}
									event.preventDefault();
									return false;
								});
							break;
						}
					}
					if( options.validateOnBlur ) {
						input
							.off('blur.mitsoft')
							.on('blur.mitsoft', function() {
								if( options.allowBlank && !$.trim($(this).val()).length ) {
									$(this).val(null);
									datetimepicker.data('mitsoft_datetime').empty();
								}else if( !Date.parseDate( $(this).val(), options.format ) ) {
									$(this).val((_mitsoft_datetime.now()).dateFormat( options.format ));
									datetimepicker.data('mitsoft_datetime').setCurrentTime($(this).val());
								}
								else{
									datetimepicker.data('mitsoft_datetime').setCurrentTime($(this).val());
 								}
								datetimepicker.trigger('changedatetime.mitsoft');
							});
					}
					options.dayOfWeekStartPrev = (options.dayOfWeekStart==0)?6:options.dayOfWeekStart-1;
					datetimepicker
						.trigger('xchange.mitsoft');
				};

				datetimepicker
					.data('options',options)
					.on('mousedown.mitsoft',function( event ) {
						event.stopPropagation();
						event.preventDefault();
						yearselect.hide();
						monthselect.hide();
						return false;
					});

				var scroll_element = timepicker.find('.mitsoft_time_box');
				scroll_element.append(timebox);
				scroll_element.mitsoftScroller();
				datetimepicker.on('afterOpen.mitsoft',function() {
					scroll_element.mitsoftScroller();
				});

				datetimepicker
					.append(datepicker)
					.append(timepicker);

				if( options.withoutCopyright!==true )
					datetimepicker
						.append(mitsoft_copyright);

				datepicker
					.append(mounth_picker)
					.append(calendar);

				$('body').append(datetimepicker);

				var _mitsoft_datetime = new function() {
					var _this = this;
					_this.now = function() {
						var d = new Date();
						if( options.yearOffset )
							d.setFullYear(d.getFullYear()+options.yearOffset);
						return d;
					};

					_this.currentTime = this.now();
					_this.isValidDate = function (d) {
						if ( Object.prototype.toString.call(d) !== "[object Date]" )
							return false;
						return !isNaN(d.getTime());
					};

					_this.setCurrentTime = function( dTime) {
						_this.currentTime = (typeof dTime == 'string')? _this.strtodatetime(dTime) : _this.isValidDate(dTime) ? dTime: _this.now();
						datetimepicker.trigger('xchange.mitsoft');
					};

					_this.empty = function() {
						_this.currentTime = null;
					};

					_this.getCurrentTime = function( dTime) {
						return _this.currentTime;
					};

					_this.nextMonth = function() {
						var month = _this.currentTime.getMonth()+1;
						if( month==12 ) {
							_this.currentTime.setFullYear(_this.currentTime.getFullYear()+1);
							month = 0;
						}
						_this.currentTime.setDate(
							Math.min(
								Date.daysInMonth[month],
								_this.currentTime.getDate()
							)
						)
						_this.currentTime.setMonth(month);
						options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						datetimepicker.trigger('xchange.mitsoft');
						return month;
					};

					_this.prevMonth = function() {
						var month = _this.currentTime.getMonth()-1;
						if( month==-1 ) {
							_this.currentTime.setFullYear(_this.currentTime.getFullYear()-1);
							month = 11;
						}
						_this.currentTime.setDate(
							Math.min(
								Date.daysInMonth[month],
								_this.currentTime.getDate()
							)
						)
						_this.currentTime.setMonth(month);
						options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						datetimepicker.trigger('xchange.mitsoft');
						return month;
					};

					_this.strtodatetime = function( sDateTime ) {
						var currentTime = sDateTime?Date.parseDate(sDateTime, options.format):_this.now();
						if( !_this.isValidDate(currentTime) )
							currentTime = _this.now();
						return currentTime;
					};

					_this.strtodate = function( sDate ) {
						var currentTime = sDate?Date.parseDate(sDate, options.formatDate):_this.now();
						if( !_this.isValidDate(currentTime) )
							currentTime = _this.now();
						return currentTime;
					};

					_this.strtotime = function( sTime ) {
						var currentTime = sTime?Date.parseDate(sTime, options.formatTime):_this.now();
						if( !_this.isValidDate(currentTime) )
							currentTime = _this.now();
						return currentTime;
					};

					_this.str = function() {
						return _this.currentTime.dateFormat(options.format);
					};
				};
				mounth_picker
					.find('.mitsoft_today_button')
						.on('mousedown.mitsoft',function() {
							datetimepicker.data('changed',true);
							_mitsoft_datetime.setCurrentTime(0);
							datetimepicker.trigger('afterOpen.mitsoft');
						}).on('dblclick.mitsoft',function(){
							input.val( _mitsoft_datetime.str() );
							datetimepicker.trigger('close.mitsoft');
						});
				mounth_picker
					.find('.mitsoft_prev,.mitsoft_next')
						.on('mousedown.mitsoft',function() {
							var $this = $(this),
								timer = 0,
								stop = false;

							(function arguments_callee1(v) {
								var month =  _mitsoft_datetime.currentTime.getMonth();
								if( $this.hasClass( options.next ) ) {
									_mitsoft_datetime.nextMonth();
								}else if( $this.hasClass( options.prev ) ) {
									_mitsoft_datetime.prevMonth();
								}
								!stop&&(timer = setTimeout(arguments_callee1,v?v:100));
							})(500);

							$([document.body,window]).on('mouseup.mitsoft',function arguments_callee2() {
								clearTimeout(timer);
								stop = true;
								$([document.body,window]).off('mouseup.mitsoft',arguments_callee2);
							});
						});

				timepicker
					.find('.mitsoft_prev,.mitsoft_next')
						.on('mousedown.mitsoft',function() {
							var $this = $(this),
								timer = 0,
								stop = false,
								period = 110;
							(function arguments_callee4(v) {
								var pheight = timeboxparent[0].clientHeight,
									height = timebox[0].offsetHeight,
									top = Math.abs(parseInt(timebox.css('marginTop')));
								if( $this.hasClass(options.next) && (height-pheight)- options.timeHeightInTimePicker>=top ) {
									timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px')
								}else if( $this.hasClass(options.prev) && top-options.timeHeightInTimePicker>=0  ) {
									timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px')
								}
								timeboxparent.trigger('scroll_element.mitsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
								period= ( period>10 )?10:period-10;
								!stop&&(timer = setTimeout(arguments_callee4,v?v:period));
							})(500);
							$([document.body,window]).on('mouseup.mitsoft',function arguments_callee5() {
								clearTimeout(timer);
								stop = true;
								$([document.body,window])
									.off('mouseup.mitsoft',arguments_callee5);
							});
						});

				// base handler - generating a calendar and timepicker
				datetimepicker
					.on('xchange.mitsoft',function( event ) {
						var table 	=	'',
							start	= new Date(_mitsoft_datetime.currentTime.getFullYear(),_mitsoft_datetime.currentTime.getMonth(),1, 12, 0, 0),
							i = 0,
							today = _mitsoft_datetime.now();
						while( start.getDay()!=options.dayOfWeekStart )
							start.setDate(start.getDate()-1);

						//generate calendar
						table+='<table><thead><tr>';

						// days
						for(var j = 0; j<7; j++) {
							table+='<th>'+options.i18n[options.lang].dayOfWeek[(j+options.dayOfWeekStart)>6?0:j+options.dayOfWeekStart]+'</th>';
						}

						table+='</tr></thead>';
						table+='<tbody><tr>';
						var maxDate = false, minDate = false;
						if( options.maxDate!==false ) {
							maxDate = _mitsoft_datetime.strtodate(options.maxDate);
							maxDate = new Date(maxDate.getFullYear(),maxDate.getMonth(),maxDate.getDate(),23,59,59,999);
						}
						if( options.minDate!==false ) {
							minDate = _mitsoft_datetime.strtodate(options.minDate);
							minDate = new Date(minDate.getFullYear(),minDate.getMonth(),minDate.getDate());
						}
						var d,y,m,classes = [];
						while( i<_mitsoft_datetime.currentTime.getDaysInMonth()||start.getDay()!=options.dayOfWeekStart||_mitsoft_datetime.currentTime.getMonth()==start.getMonth() ) {
							classes = [];
							i++;

							d = start.getDate(); y = start.getFullYear(); m = start.getMonth();

							classes.push('mitsoft_date');

							if( ( maxDate!==false && start > maxDate )||(  minDate!==false && start < minDate ) ){
								classes.push('mitsoft_disabled');
							}

							if( _mitsoft_datetime.currentTime.getMonth()!=m ) classes.push('mitsoft_other_month');

							if( (options.defaultSelect||datetimepicker.data('changed')) && _mitsoft_datetime.currentTime.dateFormat('d.m.Y')==start.dateFormat('d.m.Y') ) {
								classes.push('mitsoft_current');
							}

							if( today.dateFormat('d.m.Y')==start.dateFormat('d.m.Y') ) {
								classes.push('mitsoft_today');
							}

							if( start.getDay()==0||start.getDay()==6||~options.weekends.indexOf(start.dateFormat('d.m.Y')) ) {
								classes.push('mitsoft_weekend');
							}

							table+='<td data-date="'+d+'" data-month="'+m+'" data-year="'+y+'"'+' class="mitsoft_date mitsoft_day_of_week'+start.getDay()+' '+ classes.join(' ')+'">'+
										'<div>'+d+'</div>'+
									'</td>';

							if( start.getDay()==options.dayOfWeekStartPrev ) {
								table+='</tr>';
							}

							start.setDate(d+1);
						}
						table+='</tbody></table>';

						calendar.html(table);

						mounth_picker.find('.mitsoft_label span').eq(0).text(options.i18n[options.lang].months[_mitsoft_datetime.currentTime.getMonth()]);
						mounth_picker.find('.mitsoft_label span').eq(1).text(_mitsoft_datetime.currentTime.getFullYear());

						// generate timebox
						var time = '',
							h = '',
							m ='',
							line_time = function line_time( h,m ) {
								var now = _mitsoft_datetime.now();
								now.setHours(h);
								h = parseInt(now.getHours());
								now.setMinutes(m);
								m = parseInt(now.getMinutes());

								classes = [];
								if( (options.maxTime!==false&&_mitsoft_datetime.strtotime(options.maxTime).getTime()<now.getTime())||(options.minTime!==false&&_mitsoft_datetime.strtotime(options.minTime).getTime()>now.getTime()))
									classes.push('mitsoft_disabled');
								if( (options.defaultSelect||datetimepicker.data('changed')) && parseInt(_mitsoft_datetime.currentTime.getHours())==parseInt(h)&&(options.step>59||Math[options.roundTime](_mitsoft_datetime.currentTime.getMinutes()/options.step)*options.step==parseInt(m)))
									classes.push('mitsoft_current');
								if( parseInt(today.getHours())==parseInt(h)&&parseInt(today.getMinutes())==parseInt(m))
									classes.push('mitsoft_today');
								time+= '<div class="mitsoft_time '+classes.join(' ')+'" data-hour="'+h+'" data-minute="'+m+'">'+now.dateFormat(options.formatTime)+'</div>';
							};

						if( !options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length ) {
							for( var i=0,j=0;i<(options.hours12?12:24);i++ ) {
								for( j=0;j<60;j+=options.step ) {
									h = (i<10?'0':'')+i;
									m = (j<10?'0':'')+j;
									line_time( h,m );
								}
							}
						}else{
							for( var i=0;i<options.allowTimes.length;i++ ) {
								h = _mitsoft_datetime.strtotime(options.allowTimes[i]).getHours();
								m = _mitsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
								line_time( h,m );
							}
						}

						timebox.html(time);

						var opt = '',
							i = 0;

						for( i = parseInt(options.yearStart,10)+options.yearOffset;i<= parseInt(options.yearEnd,10)+options.yearOffset;i++ ) {
							opt+='<div class="mitsoft_option '+(_mitsoft_datetime.currentTime.getFullYear()==i?'mitsoft_current':'')+'" data-value="'+i+'">'+i+'</div>';
						}
						yearselect.children().eq(0)
												.html(opt);

						for( i = 0,opt = '';i<= 11;i++ ) {
							opt+='<div class="mitsoft_option '+(_mitsoft_datetime.currentTime.getMonth()==i?'mitsoft_current':'')+'" data-value="'+i+'">'+options.i18n[options.lang].months[i]+'</div>';
						}
						monthselect.children().eq(0).html(opt);
						$(this).trigger('generate.mitsoft');
						event.stopPropagation();
					})
					.on('afterOpen.mitsoft',function() {
						if( options.timepicker && timebox.find('.mitsoft_current').length ) {
							var pheight = timeboxparent[0].clientHeight,
								height = timebox[0].offsetHeight,
								top = timebox.find('.mitsoft_current').index()*options.timeHeightInTimePicker+1;
							if( (height-pheight)<top )
								top = height-pheight;
							timebox.css('marginTop','-'+parseInt(top)+'px');
							timeboxparent.trigger('scroll_element.mitsoft_scroller',[parseInt(top)/(height-pheight)]);
						}
					});
				var timerclick = 0;
				calendar
					.on('click.mitsoft','td',function() {
						timerclick++;
						var $this = $(this),
							currentTime = _mitsoft_datetime.currentTime;
						if( $this.hasClass('mitsoft_disabled') )
							return false;

						currentTime.setFullYear( $this.data('year') );
						currentTime.setMonth( $this.data('month') );
						currentTime.setDate( $this.data('date') );
						datetimepicker.trigger('select.mitsoft',[currentTime]);

						input.val( _mitsoft_datetime.str() );
						if( (timerclick>1||(options.closeOnDateSelect===true||( options.closeOnDateSelect===0&&!options.timepicker )))&&!options.inline ) {
							datetimepicker.trigger('close.mitsoft');
						}

						if( options.onSelectDate &&	options.onSelectDate.call ) {
							options.onSelectDate.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						}

						datetimepicker.data('changed',true);
						datetimepicker.trigger('xchange.mitsoft');
						datetimepicker.trigger('changedatetime.mitsoft');
						setTimeout(function(){
							timerclick = 0;
						},200);
					});

				timebox
					.on('click.mitsoft','div',function() {
						var $this = $(this),
							currentTime = _mitsoft_datetime.currentTime;
						if( $this.hasClass('mitsoft_disabled') )
							return false;
						currentTime.setHours($this.data('hour'));
						currentTime.setMinutes($this.data('minute'));
						datetimepicker.trigger('select.mitsoft',[currentTime]);

						datetimepicker.data('input').val( _mitsoft_datetime.str() );

						!options.inline&&datetimepicker.trigger('close.mitsoft');

						if( options.onSelectTime&&options.onSelectTime.call ) {
							options.onSelectTime.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						}
						datetimepicker.data('changed',true);
						datetimepicker.trigger('xchange.mitsoft');
						datetimepicker.trigger('changedatetime.mitsoft');
					});

				datetimepicker.mousewheel&&datepicker.mousewheel(function(event, delta, deltaX, deltaY) {
					if( !options.scrollMonth )
						return true;
					if( delta<0 )
						_mitsoft_datetime.nextMonth();
					else
						_mitsoft_datetime.prevMonth();
					return false;
				});

				datetimepicker.mousewheel&&timeboxparent.unmousewheel().mousewheel(function(event, delta, deltaX, deltaY) {
					if( !options.scrollTime )
						return true;
					var pheight = timeboxparent[0].clientHeight,
						height = timebox[0].offsetHeight,
						top = Math.abs(parseInt(timebox.css('marginTop'))),
						fl = true;
					if( delta<0 && (height-pheight)-options.timeHeightInTimePicker>=top ) {
						timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px');
						fl = false;
					}else if( delta>0&&top-options.timeHeightInTimePicker>=0 ) {
						timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px');
						fl = false;
					}
					timeboxparent.trigger('scroll_element.mitsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
					event.stopPropagation();
					return fl;
				});

				datetimepicker
					.on('changedatetime.mitsoft',function() {
						if( options.onChangeDateTime&&options.onChangeDateTime.call )
							options.onChangeDateTime.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
					})
					.on('generate.mitsoft',function() {
						if( options.onGenerate&&options.onGenerate.call )
							options.onGenerate.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
					});

				var current_time_index = 0;
				input.mousewheel&&input.mousewheel(function( event, delta, deltaX, deltaY ) {
					if( !options.scrollInput )
						return true;
					if( !options.datepicker && options.timepicker ) {
						current_time_index = timebox.find('.mitsoft_current').length?timebox.find('.mitsoft_current').eq(0).index():0;
						if( current_time_index+delta>=0&&current_time_index+delta<timebox.children().length )
							current_time_index+=delta;
						timebox.children().eq(current_time_index).length&&timebox.children().eq(current_time_index).trigger('mousedown');
						return false;
					}else if( options.datepicker && !options.timepicker ) {
						datepicker.trigger( event, [delta, deltaX, deltaY]);
						input.val&&input.val( _mitsoft_datetime.str() );
						datetimepicker.trigger('changedatetime.mitsoft');
						return false;
					}
				});
				var setPos = function() {
					var offset = datetimepicker.data('input').offset(), top = offset.top+datetimepicker.data('input')[0].offsetHeight-1, left = offset.left;
					if( top+datetimepicker[0].offsetHeight>$(window).height()+$(window).scrollTop() )
						top = offset.top-datetimepicker[0].offsetHeight+1;
					if( left+datetimepicker[0].offsetWidth>$(window).width() )
						left = offset.left-datetimepicker[0].offsetWidth+datetimepicker.data('input')[0].offsetWidth;
					datetimepicker.css({
						left:left,
						top:top
					});
				};
				datetimepicker
					.on('open.mitsoft', function() {
						var onShow = true;
						if( options.onShow&&options.onShow.call) {
							onShow = options.onShow.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						}
						if( onShow!==false ) {
							datetimepicker.show();
							datetimepicker.trigger('afterOpen.mitsoft');
							setPos();
							$(window)
								.off('resize.mitsoft',setPos)
								.on('resize.mitsoft',setPos);

							if( options.closeOnWithoutClick ) {
								$([document.body,window]).on('mousedown.mitsoft',function arguments_callee6() {
									datetimepicker.trigger('close.mitsoft');
									$([document.body,window]).off('mousedown.mitsoft',arguments_callee6);
								});
							}
						}
					})
					.on('close.mitsoft', function( event ) {
						var onClose = true;
						if( options.onClose&&options.onClose.call ) {
							onClose=options.onClose.call(datetimepicker,_mitsoft_datetime.currentTime,datetimepicker.data('input'));
						}
						if( onClose!==false&&!options.opened&&!options.inline ) {
							datetimepicker.hide();
						}
						event.stopPropagation();
					})
					.data('input',input);

				var timer = 0,
					timer1 = 0;

				datetimepicker.data('mitsoft_datetime',_mitsoft_datetime);
				datetimepicker.setOptions(options);

				var ct = options.value?options.value:(input&&input.val&&input.val())?input.val():'';
				if( ct && _mitsoft_datetime.isValidDate(ct = Date.parseDate(ct, options.format)) ) {
					datetimepicker.data('changed',true);
				}else
					ct = '';

				_mitsoft_datetime.setCurrentTime( ct?ct:0 );

				datetimepicker.trigger('afterOpen.mitsoft');

				input
					.data( 'mitsoft_datetimepicker',datetimepicker )
					.on('open.mitsoft focusin.mitsoft mousedown.mitsoft',function(event) {
						if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
							return;
						clearTimeout(timer);
						timer = setTimeout(function() {
							if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
								return;
							_mitsoft_datetime.setCurrentTime((input&&input.val&&input.val())?input.val():0);
							datetimepicker.trigger('open.mitsoft');
						},100);
					})
					.on('keydown.mitsoft',function( event ) {
						var val = this.value,
							key = event.which;
						switch(true) {
							case !!~([ENTER].indexOf(key)):
								var elementSelector = $("input:visible,textarea:visible");
								datetimepicker.trigger('close.mitsoft');
								elementSelector.eq(elementSelector.index(this) + 1).focus();
							return false;
							case !!~[TAB].indexOf(key):
								datetimepicker.trigger('close.mitsoft');
							return true;
						}
					});
			},
			destroyDateTimePicker = function( input ) {
				var datetimepicker = input.data('mitsoft_datetimepicker');
				if( datetimepicker ) {
					datetimepicker.data('mitsoft_datetime',null);
					datetimepicker.remove();
					input
						.data( 'mitsoft_datetimepicker',null )
						.off( 'open.mitsoft focusin.mitsoft focusout.mitsoft mousedown.mitsoft blur.mitsoft keydown.mitsoft' );
					$(window).off('resize.mitsoft');
					$([window,document.body]).off('mousedown.mitsoft');
					input.unmousewheel&&input.unmousewheel();
				}
			};
		$(document)
			.off('keydown.mitsoftctrl keyup.mitsoftctrl')
			.on('keydown.mitsoftctrl',function(e) {
				if ( e.keyCode == CTRLKEY )
					ctrlDown = true;
			})
			.on('keyup.mitsoftctrl',function(e) {
				if ( e.keyCode == CTRLKEY )
					ctrlDown = false;
			});
		return this.each(function() {
			var datetimepicker;
			if( datetimepicker = $(this).data('mitsoft_datetimepicker') ) {
				if( $.type(opt) === 'string' ) {
					switch(opt) {
						case 'show':
							$(this).select().focus();
							datetimepicker.trigger( 'open.mitsoft' );
						break;
						case 'hide':
							datetimepicker.trigger('close.mitsoft');
						break;
						case 'destroy':
							destroyDateTimePicker($(this));
						break;
						case 'reset':
							this.value = this.defaultValue;
							if(!this.value || !datetimepicker.data('mitsoft_datetime').isValidDate(Date.parseDate(this.value, options.format)))
								datetimepicker.data('changed',false);
							datetimepicker.data('mitsoft_datetime').setCurrentTime(this.value);
						break;
					}
				}else{
					datetimepicker
						.setOptions(opt);
				}
				return 0;
			}else
				($.type(opt) !== 'string')&&createDateTimePicker($(this));
		});
	};
})( jQuery );
/*
 * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, version 2.1.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 * details.
 */
Date.parseFunctions = {
  count: 0
};
Date.parseRegexes = [];
Date.formatFunctions = {
  count: 0
};
Date.prototype.dateFormat = function (format) {
  if (Date.formatFunctions[format] == null) {
    Date.createNewFormat(format)
  }
  var func = Date.formatFunctions[format];
  return this[func]()
};
Date.createNewFormat = function (format) {
  var funcName = "format" + Date.formatFunctions.count++;
  Date.formatFunctions[format] = funcName;
  var code = "Date.prototype." + funcName + " = function() {return ";
  var special = false;
  var ch = '';
  for (var i = 0; i < format.length; ++i) {
    ch = format.charAt(i);
    if (!special && ch == "\\") {
      special = true
    } else if (special) {
      special = false;
      code += "'" + String.escape(ch) + "' + "
    } else {
      code += Date.getFormatCode(ch)
    }
  }
  eval(code.substring(0, code.length - 3) + ";}")
};
Date.getFormatCode = function (character) {
  switch (character) {
  case "d":
    return "String.leftPad(this.getDate(), 2, '0') + ";
  case "D":
    return "Date.dayNames[this.getDay()].substring(0, 3) + ";
  case "j":
    return "this.getDate() + ";
  case "l":
    return "Date.dayNames[this.getDay()] + ";
  case "S":
    return "this.getSuffix() + ";
  case "w":
    return "this.getDay() + ";
  case "z":
    return "this.getDayOfYear() + ";
  case "W":
    return "this.getWeekOfYear() + ";
  case "F":
    return "Date.monthNames[this.getMonth()] + ";
  case "m":
    return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
  case "M":
    return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
  case "n":
    return "(this.getMonth() + 1) + ";
  case "t":
    return "this.getDaysInMonth() + ";
  case "L":
    return "(this.isLeapYear() ? 1 : 0) + ";
  case "Y":
    return "this.getFullYear() + ";
  case "y":
    return "('' + this.getFullYear()).substring(2, 4) + ";
  case "a":
    return "(this.getHours() < 12 ? 'am' : 'pm') + ";
  case "A":
    return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
  case "g":
    return "((this.getHours() %12) ? this.getHours() % 12 : 12) + ";
  case "G":
    return "this.getHours() + ";
  case "h":
    return "String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";
  case "H":
    return "String.leftPad(this.getHours(), 2, '0') + ";
  case "i":
    return "String.leftPad(this.getMinutes(), 2, '0') + ";
  case "s":
    return "String.leftPad(this.getSeconds(), 2, '0') + ";
  case "O":
    return "this.getGMTOffset() + ";
  case "T":
    return "this.getTimezone() + ";
  case "Z":
    return "(this.getTimezoneOffset() * -60) + ";
  default:
    return "'" + String.escape(character) + "' + "
  }
};
Date.parseDate = function (input, format) {
  if (Date.parseFunctions[format] == null) {
    Date.createParser(format)
  }
  var func = Date.parseFunctions[format];
  return Date[func](input)
};
Date.createParser = function (format) {
  var funcName = "parse" + Date.parseFunctions.count++;
  var regexNum = Date.parseRegexes.length;
  var currentGroup = 1;
  Date.parseFunctions[format] = funcName;
  var code = "Date." + funcName + " = function(input) {\n" + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1;\n" + "var d = new Date();\n" + "y = d.getFullYear();\n" + "m = d.getMonth();\n" + "d = d.getDate();\n" + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n" + "if (results && results.length > 0) {";
  var regex = "";
  var special = false;
  var ch = '';
  for (var i = 0; i < format.length; ++i) {
    ch = format.charAt(i);
    if (!special && ch == "\\") {
      special = true
    } else if (special) {
      special = false;
      regex += String.escape(ch)
    } else {
      obj = Date.formatCodeToRegex(ch, currentGroup);
      currentGroup += obj.g;
      regex += obj.s;
      if (obj.g && obj.c) {
        code += obj.c
      }
    }
  }
  code += "if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n" + "{return new Date(y, m, d, h, i, s);}\n" + "else if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n" + "{return new Date(y, m, d, h, i);}\n" + "else if (y > 0 && m >= 0 && d > 0 && h >= 0)\n" + "{return new Date(y, m, d, h);}\n" + "else if (y > 0 && m >= 0 && d > 0)\n" + "{return new Date(y, m, d);}\n" + "else if (y > 0 && m >= 0)\n" + "{return new Date(y, m);}\n" + "else if (y > 0)\n" + "{return new Date(y);}\n" + "}return null;}";
  Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
  eval(code)
};
Date.formatCodeToRegex = function (character, currentGroup) {
  switch (character) {
  case "D":
    return {
      g: 0,
      c: null,
      s: "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"
    };
  case "j":
  case "d":
    return {
      g: 1,
      c: "d = parseInt(results[" + currentGroup + "], 10);\n",
      s: "(\\d{1,2})"
    };
  case "l":
    return {
      g: 0,
      c: null,
      s: "(?:" + Date.dayNames.join("|") + ")"
    };
  case "S":
    return {
      g: 0,
      c: null,
      s: "(?:st|nd|rd|th)"
    };
  case "w":
    return {
      g: 0,
      c: null,
      s: "\\d"
    };
  case "z":
    return {
      g: 0,
      c: null,
      s: "(?:\\d{1,3})"
    };
  case "W":
    return {
      g: 0,
      c: null,
      s: "(?:\\d{2})"
    };
  case "F":
    return {
      g: 1,
      c: "m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
      s: "(" + Date.monthNames.join("|") + ")"
    };
  case "M":
    return {
      g: 1,
      c: "m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
      s: "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"
    };
  case "n":
  case "m":
    return {
      g: 1,
      c: "m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
      s: "(\\d{1,2})"
    };
  case "t":
    return {
      g: 0,
      c: null,
      s: "\\d{1,2}"
    };
  case "L":
    return {
      g: 0,
      c: null,
      s: "(?:1|0)"
    };
  case "Y":
    return {
      g: 1,
      c: "y = parseInt(results[" + currentGroup + "], 10);\n",
      s: "(\\d{4})"
    };
  case "y":
    return {
      g: 1,
      c: "var ty = parseInt(results[" + currentGroup + "], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
      s: "(\\d{1,2})"
    };
  case "a":
    return {
      g: 1,
      c: "if (results[" + currentGroup + "] == 'am') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}",
      s: "(am|pm)"
    };
  case "A":
    return {
      g: 1,
      c: "if (results[" + currentGroup + "] == 'AM') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}",
      s: "(AM|PM)"
    };
  case "g":
  case "G":
  case "h":
  case "H":
    return {
      g: 1,
      c: "h = parseInt(results[" + currentGroup + "], 10);\n",
      s: "(\\d{1,2})"
    };
  case "i":
    return {
      g: 1,
      c: "i = parseInt(results[" + currentGroup + "], 10);\n",
      s: "(\\d{2})"
    };
  case "s":
    return {
      g: 1,
      c: "s = parseInt(results[" + currentGroup + "], 10);\n",
      s: "(\\d{2})"
    };
  case "O":
    return {
      g: 0,
      c: null,
      s: "[+-]\\d{4}"
    };
  case "T":
    return {
      g: 0,
      c: null,
      s: "[A-Z]{3}"
    };
  case "Z":
    return {
      g: 0,
      c: null,
      s: "[+-]\\d{1,5}"
    };
  default:
    return {
      g: 0,
      c: null,
      s: String.escape(character)
    }
  }
};
Date.prototype.getTimezone = function () {
  return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/, "$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/, "$1$2$3")
};
Date.prototype.getGMTOffset = function () {
  return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0") + String.leftPad(Math.abs(this.getTimezoneOffset()) % 60, 2, "0")
};
Date.prototype.getDayOfYear = function () {
  var num = 0;
  Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
  for (var i = 0; i < this.getMonth(); ++i) {
    num += Date.daysInMonth[i]
  }
  return num + this.getDate() - 1
};
Date.prototype.getWeekOfYear = function () {
  var now = this.getDayOfYear() + (4 - this.getDay());
  var jan1 = new Date(this.getFullYear(), 0, 1);
  var then = (7 - jan1.getDay() + 4);
  document.write(then);
  return String.leftPad(((now - then) / 7) + 1, 2, "0")
};
Date.prototype.isLeapYear = function () {
  var year = this.getFullYear();
  return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)))
};
Date.prototype.getFirstDayOfMonth = function () {
  var day = (this.getDay() - (this.getDate() - 1)) % 7;
  return (day < 0) ? (day + 7) : day
};
Date.prototype.getLastDayOfMonth = function () {
  var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
  return (day < 0) ? (day + 7) : day
};
Date.prototype.getDaysInMonth = function () {
  Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
  return Date.daysInMonth[this.getMonth()]
};
Date.prototype.getSuffix = function () {
  switch (this.getDate()) {
  case 1:
  case 21:
  case 31:
    return "st";
  case 2:
  case 22:
    return "nd";
  case 3:
  case 23:
    return "rd";
  default:
    return "th"
  }
};
String.escape = function (string) {
  return string.replace(/('|\\)/g, "\\$1")
};
String.leftPad = function (val, size, ch) {
  var result = new String(val);
  if (ch == null) {
    ch = " "
  }
  while (result.length < size) {
    result = ch + result
  }
  return result
};
Date.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Date.y2kYear = 50;
Date.monthNumbers = {
  Jan: 0,
  Feb: 1,
  Mar: 2,
  Apr: 3,
  May: 4,
  Jun: 5,
  Jul: 6,
  Aug: 7,
  Sep: 8,
  Oct: 9,
  Nov: 10,
  Dec: 11
};
Date.patterns = {
  ISO8601LongPattern: "Y-m-d H:i:s",
  ISO8601ShortPattern: "Y-m-d",
  ShortDatePattern: "n/j/Y",
  LongDatePattern: "l, F d, Y",
  FullDateTimePattern: "l, F d, Y g:i:s A",
  MonthDayPattern: "F d",
  ShortTimePattern: "g:i A",
  LongTimePattern: "g:i:s A",
  SortableDateTimePattern: "Y-m-d\\TH:i:s",
  UniversalSortableDateTimePattern: "Y-m-d H:i:sO",
  YearMonthPattern: "F, Y"
};

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory
  } else {
    factory(jQuery)
  }
}(function ($) {
  var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
  var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
  var lowestDelta, lowestDeltaXY;
  if ($.event.fixHooks) {
    for (var i = toFix.length; i;) {
      $.event.fixHooks[toFix[--i]] = $.event.mouseHooks
    }
  }
  $.event.special.mousewheel = {
    setup: function () {
      if (this.addEventListener) {
        for (var i = toBind.length; i;) {
          this.addEventListener(toBind[--i], handler, false)
        }
      } else {
        this.onmousewheel = handler
      }
    }, teardown: function () {
      if (this.removeEventListener) {
        for (var i = toBind.length; i;) {
          this.removeEventListener(toBind[--i], handler, false)
        }
      } else {
        this.onmousewheel = null
      }
    }
  };
  $.fn.extend({
    mousewheel: function (fn) {
      return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel")
    }, unmousewheel: function (fn) {
      return this.unbind("mousewheel", fn)
    }
  });

  function handler(event) {
    var orgEvent = event || window.event,
      args = [].slice.call(arguments, 1),
      delta = 0,
      deltaX = 0,
      deltaY = 0,
      absDelta = 0,
      absDeltaXY = 0,
      fn;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    if (orgEvent.wheelDelta) {
      delta = orgEvent.wheelDelta
    }
    if (orgEvent.detail) {
      delta = orgEvent.detail * -1
    }
    if (orgEvent.deltaY) {
      deltaY = orgEvent.deltaY * -1;
      delta = deltaY
    }
    if (orgEvent.deltaX) {
      deltaX = orgEvent.deltaX;
      delta = deltaX * -1
    }
    if (orgEvent.wheelDeltaY !== undefined) {
      deltaY = orgEvent.wheelDeltaY
    }
    if (orgEvent.wheelDeltaX !== undefined) {
      deltaX = orgEvent.wheelDeltaX * -1
    }
    absDelta = Math.abs(delta);
    if (!lowestDelta || absDelta < lowestDelta) {
      lowestDelta = absDelta
    }
    absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
    if (!lowestDeltaXY || absDeltaXY < lowestDeltaXY) {
      lowestDeltaXY = absDeltaXY
    }
    fn = delta > 0 ? 'floor' : 'ceil';
    delta = Math[fn](delta / lowestDelta);
    deltaX = Math[fn](deltaX / lowestDeltaXY);
    deltaY = Math[fn](deltaY / lowestDeltaXY);
    args.unshift(event, delta, deltaX, deltaY);
    return ($.event.dispatch || $.event.handle).apply(this, args)
  }
}));